Brownman Revival
Brownman Revival

Reputation: 3850

input type number, accepts number only not letter jquery

$("#number").bind('keyup change click', function() {
            if ($(this).val().match(/^\d+$/)) {

            } else {
                alert("Not a number");
            }

This is my code for getting input that is number only from user. It is ok but I got some problem with the start of click; when I click it will alert that it is not a number even if it is still empty so i added another code:

if ($(this).val().length === 0) {
}

from the start of the the code. It did fix the problem with empty or starting click the problem is when I type in letters it does not alert the message anymore. How to fix this one?any suggestion is appreciated

Upvotes: 1

Views: 1346

Answers (2)

lshettyl
lshettyl

Reputation: 8171

@Rias has the answer above, but, you could also do the following.

$("#number").bind('keyup change click', function() {
    //Check only if the text box is not empty
    if ( $.trim($(this).val()) != "") {
        if ($(this).val().match(/^\d+$/)) {
        } else {
            alert("Not a number");
        }
    }
});

Demo@Fiddle

Update: In case you wanted to remove any the non-number characters, try the following.

$("#number").bind('keyup change click', function() {

    if ( $.trim($(this).val()) != "") {
        if ($(this).val().match(/^\d+$/)) {
        } else {
            alert("Not a number");
            $(this).val( $(this).val().replace(/[^0-9]+/gi, "") );
        }
    }
});

Upvotes: 2

Rias
Rias

Reputation: 1996

Change the regular expression to /^\d*$/ and it will accept an empty field also, because the quantifier * accepts 0 or more characters of the type \d number, whereas + needs 1 or more numbers to match.

$(document).ready(function() {


  $("#number").bind('keyup change click', function() {
    if ($(this).val().match(/^\d*$/)) {

    } else {
      alert("Not a number");
    }
  });

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

Upvotes: 1

Related Questions