0

I need to make sure input on dynamically generated input fields accept only numbers.

This jsfiddle is doing exactly what I want but it isn't allowing for dynamically generated fields: http://jsfiddle.net/lesson8/HkEuf/1/.

I've modified it to work with a function but it isn't doing anything. Any ideas what I'm doing wrong?

HTML:

Number : <input onkeydown="test(this);" type="text" name="quantity" id="quantity" />&nbsp;<span id="errmsg"></span>

Javascript:

function test(input) {
  //called when key is pressed in textbox
  input.keypress(function (e) {
     //if the letter is not digit then display error and don't type anything
     if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        //display error message
        $("#errmsg").html("Digits Only").show().fadeOut("slow");
               return false;
    }
   });
}

CSS:

#errmsg
{
color: red;
}

Function version: http://jsfiddle.net/HkEuf/4776/

4thSpace
  • 41,122
  • 88
  • 267
  • 450

2 Answers2

0

You should use .delegate.

 $('#container', 'input', 'keypress', function() {
     // your code here
 });
Daniel A. White
  • 174,715
  • 42
  • 343
  • 413
0

Try this:

<input value="" onkeypress="return onlyNumber(event)" />

<script type="text/javascript">

function onlyNumber(e) {
    e = (e) ? e : window.event;
    var charCode = (e.which) ? e.which : e.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

</script>
Mouhamad Kawas
  • 340
  • 2
  • 12