Sugumar Venkatesan
Sugumar Venkatesan

Reputation: 4028

Disallow some numbers in form input field in jQuery

In the form input field I want to display numbers like scroll option but I want to disable some numbers, which I get from the database.

For example, if my database query returns 3,5 and 7, the user should not be able to input those numbers in the form input field.

<form>
<input name="sid" type="number">
</form>

Upvotes: 0

Views: 58

Answers (2)

Manwal
Manwal

Reputation: 23816

You can do something like this:

$(function(){  
    var preventNumbers = [3,4,5] //array of numbers
    $('input[name="sid"]').keydown(function(e){
        if(preventNumbers.indexOf(parseInt(String.fromCharCode(e.which))) > -1){
        return false;
    }
  });
})

DEMO

Here I have created array of numbers which you want to prevent from type in input, and with keydown function you can prevent it.

If you want to prevent arrow event also then you have to catch the mouseup event like:

$(function(){  
    var preventNumbers = [3,4,5]
    $('input[name="sid"]').keydown(function(e){
        if(preventNumbers.indexOf(parseInt(String.fromCharCode(e.which))) > -1)         {
        return false;
    }
  }).mouseup(function(){
        var val = $(this).val();
    if(preventNumbers.indexOf(parseInt(val)) > -1)          {
        $(this).val('');
    }
  })
})

Updated DEMO

Upvotes: 2

Luke P
Luke P

Reputation: 734

IF you are using jQuery, you can bind to the keyup event, and check the key that was pressed, then return false if it's one that you don't want the user to select:

$("input").keypress(function(e) {
    if ( event.which == 13 ) {
        event.preventDefault();
    }
});

Upvotes: 0

Related Questions