0

$('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
Pekka
  • 1,075
  • 2
  • 10
  • 17
  • Can you use `` saves you all the hassle of an additional check using js. http://www.htmlgoodies.com/html5/tutorials/whats-new-in-html5-forms-handling-numeric-inputs-using-the-number-and-range-input-types.html#fbid=w1ah_NK1kue – Clyde Lobo Mar 02 '17 at 08:54
  • @ClydeLobo i dont like the updown keys in the input using number type – Pekka Mar 02 '17 at 08:57

2 Answers2

2

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="" />
mplungjan
  • 169,008
  • 28
  • 173
  • 236
1

Simply replace any non-numeric symbol to empty string:

$('input').on("input", function(e) {
    $(this).val($(this).val().replace(/[^\d]/, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
Justinas
  • 41,402
  • 5
  • 66
  • 96