I’ve found that using .keyup() in jQuery doesn’t always work like I want. For example, if I want to ensure that a user can’t put a special character into an input field I want to check for that character every time the input changes. Only using .keyup() allows someone to right-click and paste a bad value in.
Instead I use .bind(“change keyup input”) to catch all changes on an input field, regardless of how they are done.
For example:
// detect the change
$('input#myId').bind("change keyup input",function() {
// if there's a bad value
if (this.value.match(/[^a-zA-Z0-9\-_\s]/g)) {
// replace it with nothing
this.value = this.value.replace(/[^a-zA-Z0-9\-_\s]/g, '');
}
});
Pretty simple, eh?
If you liked this you should follow me on Twitter where I tweet about startups, code, and other useful things.




Pingback: Learning by prototyping with building block « Peter Bakker