0

Iam creating a dynamic input and applying a class to it, but its not working.
My class:

$(".numeric_input").keypress(function(e) {
    var a = [];
    var k = e.which;
    for (i = 48; i < 58; i++)
       a.push(i);
    if (!(a.indexOf(k)>=0))
       e.preventDefault();
});

My code:

var table = document.getElementById('sizeTable');
for(var i=0;i<sizes.length;i++) {
    $("<td></td>").html('<input type=text class=numeric_input name=rows['+i+'].quantity>').appendTo(tr);
    $(tr).appendTo(table);
}

The same class applied to other elements are working fine. Any help

Derek Henderson
  • 9,388
  • 4
  • 42
  • 71
vivek
  • 4,599
  • 3
  • 25
  • 37
  • Is the class not applied or does the event handler not work? I see `class=numeric_input` in your code, so I don't see a reason why the element should not have that class. – Felix Kling Jun 07 '13 at 11:13
  • The class is applied, I can see via inspectElement but event handler is not working. It is accepting all values – vivek Jun 07 '13 at 11:14

2 Answers2

3

Because you are creating .numeric_input dynamically, you need to target the event differently. Instead of .keypress() use .on():

$(document).on('keypress', '.numeric_input', function (e) {
    var a = [];
    var k = e.which;
    for (i = 48; i < 58; i++)
       a.push(i);
    if (!(a.indexOf(k) >= 0))
       e.preventDefault();
});
Derek Henderson
  • 9,388
  • 4
  • 42
  • 71
2

Use event delegation (as your .numeric_input being added dynamically)

$(document).on('keypress',".numeric_input",function(e) {
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111