I would like to use the following code to restrict input (to alphanumeric) into a text field:
$('input').bind('keypress', function (event) {
var regex = new RegExp("^[a-zA-Z0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
});
The above code works great on a standard input field, but when I type into a field generated by Chosen, the function is not applied. The chosen plugin does generate a div containing <input type="text"> but $('input') doesn’t seem to touch it. I’m guessing this is due to the timing of when the above code is applied..
Jack’s answer works. But the important thing to understand is that the keypress event bubbles, so you can catch it anywhere up the node hierarchy, at a node that is not generated dynamically.
http://jsfiddle.net/KWv7Z/6/
This is also more memory friendly since it doesn’t install a separate handler per input on the page.