0

How can I make an input element accept numbers only in multiples of 50?

I know we can specify step="50" as an attribute, but I would prefer a solution that is triggered by the keyup event.

I found this code, which prevents users from entering a number less than 50.

Question : How can I adjust this code so that only multiples of 50 can be entered ?

$('#numberbox').keyup(function(){
  if ($(this).val() < 50){
    alert("Minimum Quantity: 50");
    $(this).val('50');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="numberbox" type='number'>

3 Answers 3

2

Use the modulo operator

var multiple = 50;

$('#numberbox').keyup(function(){
   if (parseInt($(this).val()) % multiple ) {
      alert("Only multiples of " + multiple + " allowed");
      $(this).val(multiple);
   }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks , This is what i am looking for :)
1

I would prefer blur instead of keyup as keyup would keep on alerting. To know if it is multiple of 50 check a condition with modulo i.e.% like if parseInt($(this).val())%50 != 0

$('#numberbox').blur(function(){
  if (parseInt($(this).val())%50 != 0){
    alert("Multiples of 50 should be entered");
    $(this).val('50');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="numberbox" type='number'>

1 Comment

@wordpressuser. No probs.. Happy coding.. :)
1

You can use Remainder (%) to do this, check the example bellow.

The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend, not the divisor.

$('#numberbox').keyup(function(){
  if ($(this).val()%50==0){
    $('#result').text($(this).val()+' is multiple of 50');
  }else{
     $('#result').text($(this).val()+' is not a multiple of 50');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="numberbox" type='number'>
<span id='result'></span>

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.