Pekka Pekka -4 years ago 97
jQuery Question

checking for inputted value if numbers or letters using test



$('input').on("input", function() {
if (isWhole($(this).val())) {
return false;
//$(this).removeAttr("style").removeClass("not");
} else {
//$(this).css("border", "2px solid red").addClass("not");

}
});


function isWhole(n) {
return /^\d+$/.test(n);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="" type="text" id="" />





In this OP i want to make user input only numbers. if they input letters it should not be allowed meaning it should not be written in the input.


  1. I used test to test if inputted data is number.

  2. When I comment return false when i input letters border is added. If i input numbers border is removed this is my desired out come.

  3. Tried it with return false alone. I am assuming it will not let the inputted letter to show but it is still showing.

  4. How to not let user input letters


Answer Source

Test the value and if a number allow it - or in this case, allow the number part of it

$('input').on("input", function(e) {
  var val = this.value;
  if (!isWhole(val)) {
    var num = parseInt(val);
    $(this).val(isNaN(num)?"":num);
  }
});


function isWhole(n) {
  return /^\d+$/.test(n);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="" type="text" id="" />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download