jQuery .keyup() vs .change() vs .bind()

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.

Eric is a jack of all trades. From running social networks to internet cafes, he’s been in the startup scene for almost a decade. Recently returned from a stint at Start-Up Chile, Eric spends his days focusing on his startups Backup Box and Surreal WiFi.

Facebook Twitter LinkedIn Google+ 

  • http://www.philwebservices.com/ web design philippines

    Well, thanks for this. I hope it will work on mine.

  • Pingback: Learning by prototyping with building block « Peter Bakker

  • http://hearingtracker.com Hearing Tracker


  • Anders Sjöqvist

    Is there a reason to first check for matches before doing the replacement? Would calling replace() immediately be less performant or does it trigger more events?

  • Michael Hjulskov

    Thanks for sharing
    I think you can also use
    .on(‘keyup paste change input’)
    and get the same result, right?