Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript or jQuery to accept numbers less than 100 for text field

In my project I have a text field where I need to accept values less than or equal to 100. In that text field how can I achieve this through javascript or jquery. Somehow I have managed to accept only numbers in text box but how can i restrict it not accept numbers greater than 100.

Here is the code which I have tried to accept only numbers

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}
like image 972
Shabarinath Volam Avatar asked Apr 04 '14 11:04

Shabarinath Volam


2 Answers

First off, you can use number type in HTML5 with the max attribute set to 100.

<input id="numberbox" type='number' max='100'>

This will allow your browser to detect when it's over 100 when submitted. However, it won't work on older browsers and some smartphones.

Alternatively, you could do this:

<input type='text' maxlength='2' pattern='^[0-9]$'>

But I feel this option is overkill. But if you want to do it that way, that's up to you.

In jQuery, you can do this:

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

Please also validate back-end, someone with only just enough knowledge could easily bypass this.

like image 85
Albzi Avatar answered Oct 27 '22 09:10

Albzi


Check this demo

Also you have to restrict the length of text field

Something like this

var fieldVal = document.getElementById('txtF').value;
//Suppose u want  number that is less than 100
if(fieldVal < 100){
    return true;
}
else
{
  //
}
like image 43
Blu Avatar answered Oct 27 '22 09:10

Blu