开发者

How to validate a textbox to check if the value entered is in multiples of 100 only

开发者 https://www.devze.com 2023-03-31 13:05 出处:网络
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 #exampl

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:

  1. The boring right way

    if (parseInt(input,10) % 100 === 0)
    
  2. A bit more fun way

    if (input.substr(-2)==='00')
    
  3. "I love odd bases"

    if (parseInt(value,13) % parseInt('79',13) === 0)
    
  4. Regexes

    if (input.match(/[1-9]+00$/))
    
  5. More fun (but definitely more robust) regexes

    if (input.match(/\s*\d+0{2}\s*$/))
    
  6. 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 (parseInt($("#yourtextbox").val()) % 100 === 0) {
    // is multiple of 100
}


Use Modulo to check if the remainder is 0.

http://jsfiddle.net/jSfXC/


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');

JSFiddle Example


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.

EG

5/2 == 2 remainder 1
5 % 2 == 1 (the remainder)


if ( parseInt($('#input').val(), 10) % 100 !== 0 ) {
   alert('Value isn't a multiple of 100');
}


Try this:

$('#your_input_selector').keyup(function(){ alert('100 multiple? ' $(this).val() % 100 == 0)});
0

精彩评论

暂无评论...
验证码 换一张
取 消