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

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

Here is the code that I 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;
}
+4
source share
8 answers

First, you can use a type numberin HTML5 with an attribute maxset to 100.

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

, 100 . .

:

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

, . , .

jQuery :

$('#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'>
Hide result

, , -, , .

+6

demo

text field

-

var fieldVal = document.getElementById('txtF').value;
//Suppose u want  number that is less than 100
if(fieldVal < 100){
    return true;
}
else
{
  //
}
+2

jquery - :

$('#my-field').blur(function() {
   if(parseInt($(this).val()) < 100) {
       $(this).val('');
   }
});

, ( ). , 100 .

+1
function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    var str = String.fromCharCode(charCode);
    if (str>100)) {
        return false;
    }
    return true;
}

fromCharCode,

+1

maxlength="2" 

EX.

<!DOCTYPE html>
<html>
<body>

<form action="demo_form.asp">
  PIN: <input type="text" name="pin" maxlength="2" size="30"><br>
  <input type="submit" value="Submit">
</form>

</body>
</html>
+1

:

$('yourElem').on('keydown', function(e){
    if(this.value > 100){
       alert('You have entered more than 100 as input');
       return false;
    }
});

maxlength , :

maxlength="3"

js, , maxlength 100, .

+1

:

<script type="text/javascript">
function fnc(value, min, max) 
{
    if(parseInt(value) < 0 || isNaN(value)) 
        return 0; 
    else if(parseInt(value) > 100) 
        return "Number is greater than 100"; 
    else return value;
}
</script>
<input type="text" name="textWeight" id="txtWeight" maxlength="5" onkeyup="this.value = fnc(this.value, 0, 100)"/>
+1

, 2 char....

    if (charCode.length > 2) {
    return false;
    }
+1

Source: https://habr.com/ru/post/1535017/


All Articles