yeomandev
yeomandev

Reputation: 11796

How to use jQuery to prevent the space key from entering a space?

I thought it would be a simple thing to hijack the space key when in a form input so that it would function like a hyphen. Generally jQuery makes stuff like this really simple.

The code I tried is this:

        $("#StreamUrl").keydown(function (e) {
            if (e.keyCode == 32) return 109;
        });

But this has no effect whatsoever. I tried a more simple script:

        $("#StreamUrl").keydown(function (e) {
            //if (e.keyCode == 32) return 109;
            alert(e.keyCode);
        });

This script correctly alerts 32 on space press and 109 on hyphen press. Also, I have no JavaScript errors.

Why wouldn't if (e.keyCode == 32) return 109; work? When I replace that line with if (e.keyCode == 32) alert("space!!"); I get the alert correctly, so I know the if is returning true correctly.

What gives?

Edit - Solution

Thanks to @Nick for pointing out the copy-paste issue. I ended up with a little bit of a hybrid. Here's the code that I have gotten to work which is both smooth and handles Copy/Paste.

        $("#StreamUrl").keydown(function (e) {
            if (e.keyCode == 32) {
                $(this).val($(this).val() + "-"); // append '-' to input
                return false; // return false to prevent space from being added
            }
        }).change(function (e) {
            $(this).val(function (i, v) { return v.replace(/ /g, "-"); }); 
        });

Upvotes: 15

Views: 29403

Answers (2)

Nick Craver
Nick Craver

Reputation: 630359

You usually want the keyup event instead here, which fires after the space has been added, something like this is a bit easier:

$("#StreamUrl").bind("keyup change", function () {
  $(this).val(function(i, v) { return v.replace(/ /g,"-"); });
});

Try it out here, what this does is allow the space to be added, but then instantly does a replace of spaces for hyphens by passing a function to .val(). For older versions of jQuery, it'd look like this:

$("#StreamUrl").bind("keyup change", function () {
  $(this).val($(this).val().replace(/ /g,"-"));
});

This works even for people pasting content, an easy way to get around keydown validation.

Upvotes: 11

Cristian Sanchez
Cristian Sanchez

Reputation: 32097

The problem is that return 109 doesn't do what you want it to do. In an event handler, you return true or false depending on whether or not you want the browser to execute the default action. In keydown, you would return false to prevent the character from being inserted.

$("#StreamUrl").keydown(function (e) {
     if (e.keyCode == 32) { 
       $(this).val($(this).val() + "-"); // append '-' to input
       return false; // return false to prevent space from being added
     }
});

jsfiddle example

Upvotes: 21

Related Questions