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.
Asked
Active
Viewed 1.2k times
2
-
2But... Why can't you? – Karl-André Gagnon Feb 05 '14 at 18:40
-
2Use event delegation or rebind the handlers after creating the new forms. – Jason P Feb 05 '14 at 18:40
-
2try don't say you cant without trying... – Zaheer Ahmed Feb 05 '14 at 18:40
-
I tried but I could not because I'm still learning jQuery and I need this, can you send me some example code I would be grateful? – user3104669 Feb 05 '14 at 18:43
-
1https://learn.jquery.com/events/event-delegation/ – Jason P Feb 05 '14 at 18:44
-
1`type="number"` in the `input` ? – tymeJV Feb 05 '14 at 18:46
-
possible duplicate of [how do i block or restrict special characters from input fields with jquery?](http://stackoverflow.com/questions/895659/how-do-i-block-or-restrict-special-characters-from-input-fields-with-jquery) – bjb568 Feb 05 '14 at 18:46
2 Answers
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:

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
-
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
-
I use jquery 1.10.1 and put this in head of my site and cant make to work, what should i do? – user3104669 Feb 05 '14 at 19:13
-
Try waiting until the DOM has loaded to execute your code, see updated example above: – smithbh Feb 05 '14 at 19:18