3

I want to perform a validation only when the input field is of number type and corresponding attribute validate has value checkit. I am not sure what should I pass in place of astrix to bind this to keypress event $('*** input[type=number]').bind mentioned in the code below. I am stuck here, any help in this regard is appreciated.

<input type="number" validate="checkit">

$('input[type=number]').bind('keypress', function(e) {
    //do things here
});
yeppe
  • 679
  • 1
  • 11
  • 43
  • 1
    `$('input[type=number][validate="checkit"]').bind('keypress'.....` – Satpal Sep 20 '16 at 11:29
  • 1
    This solution doesn't work because the problem is not a selector but a time when you selecting an element. You should use 'on' to listing on dynamically changing attributes. $('form').on('keypress',''input[type=number][validate="checkit"]'', function(e){}); – cezarypiatek Sep 20 '16 at 11:37
  • @cezarypiatek thanks for your comments and .bind doesn't work for elements added dynamically that matches the same selector...http://elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/ here it says "the .on method bring a lot of consistency to the API and hopefully makes things slightly less confusing." – yeppe Sep 20 '16 at 11:47

2 Answers2

3

Try this:

$('input[type=number][validate=checkit]').bind('keypress', function(e) {
    //do things here
});
jcubic
  • 61,973
  • 54
  • 229
  • 402
  • According to this site http://elijahmanor.com/differences-between-jquery-bind-vs-live-vs-delegate-vs-on/ using .on is better ....$('input[type=number][validate=checkit]').on('keypress', function(e) { //do things here }); – yeppe Sep 20 '16 at 12:02
  • Yes I know, I copied your code. – jcubic Sep 20 '16 at 12:04
1

You can either add a condition inside your event handler, which makes your code like this:

$('input[type="number"]').bind('keypress', function(e) {
    if($(this).prop('validate') == 'checkit')
    {
       // do here
    }
});

Or you can assign a class to your input[type='number'], for instance, .input-num and then create an event listener like this:

 $('.input-num[validate="checkit"]').bind('keypress', function(e) {
        // do things here
    });

The first solution adds a memory-overhead based on the number of inputs (if there are too many of them), since an event is attached to all of them, but the code exclude inputs based on the condition which we just added.

The second solution, though, is better in terms of performance and memory, but it requires you to add class to your input[type="number"] which add some time-overhead

Mostafa Talebi
  • 8,825
  • 16
  • 61
  • 105