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?
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;
});
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. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With