2

How to disable letters on dynamcaly created HTML input forms with jQuery? I can make this for input forms which alerady exist but cant make for dynamicaly created new forms.

user3104669
  • 67
  • 1
  • 2
  • 6

2 Answers2

7

You need simply to use the "live" function of Jquery, Just as following:

$('input').live('keypress', function(key) {
    if(key.charCode < 48 || key.charCode > 57) return false;
});

This is applied on all inputs in the file, either generated on page load or on the fly, You can replace it with a class name to handle only this group of inputs if you have other inputs in the file.

Here you are a full example:

http://jsfiddle.net/tZPg4/8575/

Yazid Erman
  • 1,166
  • 1
  • 13
  • 24
  • Thanks for the code, but i put that code in head of my page and won't work, why? – user3104669 Feb 05 '14 at 18:58
  • The reason shouldn't be but names problem, Either you share with us the related parts of the code, or you check the names and debug your code well. – Yazid Erman Feb 05 '14 at 19:33
  • 4
    .live() is deprecated, use .on() instead – Jay Blanchard Feb 05 '14 at 20:14
  • thank you for the answer, but this prevent functions like delete, backspace paste. is there way to enable those functions an prevent trying letters an special characters, Thanks – Suneth Kalhara Nov 13 '18 at 18:46
  • @SunethKalhera: For sure you can exclude any character. You can refer to the list of ASCII control characters: https://theasciicode.com.ar/ – Yazid Erman Nov 21 '18 at 10:40
1

As of jQuery v1.7, "live" is deprecated. You should use "on" for event delegation. Ex:

<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    $('body').on('keyup', 'input', function() {
      // do something
    });
  });
</script>
</head>

A working example including the regex you need can be found at http://jsfiddle.net/5XXJR/

smithbh
  • 347
  • 1
  • 7