How do i restrict the number to a total of 3 on my input fields?

Viewed 63

I am trying to restrict the number of input values to only three for my two input fields. Example.. input 1 = 1, input 2 = 2. so, 1+ 2 = 3 or 2 + 1= 3, or if the value in one input reach 3, the user will not be able to add more.. there were other similar questions but they are usually only for 1 input field. I want the restriction for the combined field.

I have tried the following code and it does not seem to react the way I want it.. it does not total the value to only 3. It does this in the browser, but when I look at the console, it still continues.

$('.qty_pack').change(function() {
  var i = 0;
  if (i >= 3) {
    $(this).parent().find('.qty_pack').val(0);
    console.log('You have reached max items');
  }
  $('.check_sales_pack').each(function() {
    i += parseFloat($(this).parent().find('.qty_pack').val())
  });
  console.log(i);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <input type="hidden" class="check_sales_pack" name="check_sales_pack">
  <input type="number" class="qty_pack" name="qty_pack" value="0" min="0" max="3">
  <input type="number" class="qty_pack" name="qty_pack" value="0" min="0" max="3">
</div>

1 Answers

Check if i > 3 after iterating over the inputs and adding to i. Also, use the selector .qty_pack to select the inputs:

$('.qty_pack').change(function(e) {
  let count = 0;
  $('.qty_pack').each(function() {
    count += parseFloat(this.value);
  });
  console.log('Total:', count);
  if (count > 3) {
    // Reset the *most recently changed* input to 0:
    e.target.value = 0;
    console.log('You have reached max items');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <input type="hidden" class="check_sales_pack" name="check_sales_pack">
  <input type="number" class="qty_pack" name="qty_pack" value="0" min="0" max="3">
  <input type="number" class="qty_pack" name="qty_pack" value="0" min="0" max="3">
</div>

Keep in mind that if the calculated count has to be correct, verification should be done on the server as well, when the data gets sent to it - code that runs on the client cannot be trusted, because the client can run (and monkeypatch) any code they want.

Related