Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
145
rated 0 times [  146] [ 1]  / answers: 1 / hits: 29068  / 14 Years ago, mon, october 4, 2010, 12:00:00

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, -); });
});

More From » jquery

 Answers
133

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


[#95423] Friday, October 1, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jack

Total Points: 557
Total Questions: 96
Total Answers: 80

Location: Saint Helena
Member since Mon, Jan 16, 2023
1 Year ago
;