Search code examples
c#htmlinputblazor

Html number input handling in blazor


I am facing issue in handling max with manual input. My implimentation works like , when input value is already equal to max like 13 equal to 13 and i enter more value it becomes i.e 136. i trying its convert to 13 but its work only for 2 digits lenght like 20 converted into 13 but after it becomes 134 or 137

`

                     <td>
                <input     min="0.01" class="quantityInput"
                                type="number" step="0.01" 
                             value="@item.Quantity"   @oninput="e => UpdateQuantity(item,e)"
                max="@item.MaxQuantity" />

                     </td>

@code{
  private void UpdateQuantity(EditableSaleItemViewModel item, ChangeEventArgs e)
   {
       var input = e.Value?.ToString();
       if (double.TryParse(input, out double newQuantity))
       {
           if (newQuantity < 0)
           {
               newQuantity = 0; // Ensure it's not negative
           }
           else if (newQuantity > item.MaxQuantity)
           {
               newQuantity = item.MaxQuantity;  
           }
        
           item.Quantity = newQuantity;
           e.Value = item.Quantity;
           item.TotalPrice = Math.Round(item.Quantity * item.UnitPrice, 2);
        
       }
       else
       {
           item.Quantity = 0;  
           item.TotalPrice = 0;
       }

       totalAmount = Math.Round(editableSaleItems.Sum(i => i.TotalPrice), 2);
       StateHasChanged();
   }}
`

Solution

  • I can't create a Minimal Reproducible Example from your code, so here's a demo of how you could implement your input using binding.

    <input class="form-control"
           type="number"
           step="0.01"
           @bind:get="_quantity"
           @bind:set="this.SetQuantity"
           @bind:event="oninput" />
    
    
    @code {
        private decimal _quantity;
        private decimal _maxQuantity = 20;
    
        private void SetQuantity(decimal value)
        {
            _quantity = value;
    
            if (value > _maxQuantity)
                _quantity = _maxQuantity;
    
            if (value < 0)
                _quantity = 0;
    
                //Add other logic you want
        }
    }