Reputation: 14363
I want to validate that the value entered by a user in a textbox is a multiple of 100 using jQuery. How can I do that?
Upvotes: 3
Views: 6848
Reputation: 26941
There are a lot of fun ways. Lets collect the input value itself:
var input = $('#textbox').val();
So, ways:
The boring right way
if (parseInt(input,10) % 100 === 0)
A bit more fun way
if (input.substr(-2)==='00')
"I love odd bases"
if (parseInt(value,13) % parseInt('79',13) === 0)
Regexes
if (input.match(/[1-9]+00$/))
More fun (but definitely more robust) regexes
if (input.match(/\s*\d+0{2}\s*$/))
And the winner is...
if ((input.search(/\s*\d+0{2}\s*$/)==-1?"false":"true" !== "false"))
But if I were you I'd stop with first way. :)
Upvotes: 3
Reputation: 165971
This will check whether the value of the element matching #example
is a multiple of 100 and store the result (true
or false
) in multiple
:
$("#example").change(function() {
var multiple = parseInt($(this).val(), 10) % 100 == 0;
});
Note that this will result in 0
returning true
, so you may want to add a check in for that.
Here's a live example. See MDN article for more information on the modulus operator.
Update (based on comments)
As noted by @PaulPRO in the comments, the above will also return true for numbers such as 100.973. If you want to deal with floating point numbers as well as integers, simply use parseFloat
instead of parseInt
. Here's another live example, and here's some updated code:
$("#example").change(function() {
var multiple = parseFloat($(this).val()) % 100 == 0;
});
Upvotes: 6
Reputation: 1099
Try this:
$('#your_input_selector').keyup(function(){ alert('100 multiple? ' $(this).val() % 100 == 0)});
Upvotes: 0
Reputation: 141829
Something like this will work for you:
var input = document.getElementById('mult-100');
if(input.value.match(/^[1-9]\d*00$/))
return false;
// Not a multiple of 100
alert('Please enter a multiple of 100');
Upvotes: 1
Reputation: 22943
if ( parseInt($('#input').val(), 10) % 100 !== 0 ) {
alert('Value isn't a multiple of 100');
}
Upvotes: 0
Reputation: 16971
if (parseInt($("#yourtextbox").val()) % 100 === 0) {
// is multiple of 100
}
Upvotes: 2
Reputation: 29925
if(value % 100 == 0) { // if the remainder of a division by 100 is 0
// divides by 100
} else {
// doesn't!
}
As poweroy says this is a Modulo (see his link). Its just the percentage sign. What it does is returns the remainder of a division.
5/2 == 2 remainder 1
5 % 2 == 1 (the remainder)
Upvotes: 0