How to use jQuery to prevent the space key from entering a space?
<p>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.</p>

<p>The code I tried is this:</p>

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

<p>But this has no effect whatsoever. I tried a more simple script:</p>

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

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

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

<p>What gives?</p>

<h2>Edit - Solution</h2>

<p>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.</p>

<pre><code>        $("#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, "-"); }); 
        });
</code></pre>
