Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It doesn't "disable" the back arrow &mdash; your code keeps replacing all the text outright, whenever you press a key, and every time that happens the caret position is lost.</p> <p>Simply don't do that.</p> <p>Use a better mechanism for banning spaces, such as <a href="https://stackoverflow.com/a/11268278/560648">returning <code>false</code> from an onkeydown handler when the key pressed is <code>space</code></a>:</p> <pre><code>$(function() { $("input#Username").on("keydown", function (e) { return e.which !== 32; });​​​​​ }); </code></pre> <p>This way, your textbox is prohibited from receiving the spaces in the first place and you don't need to replace any text. The caret will thus remain unaffected.</p> <hr> <h3>Update</h3> <p><a href="https://stackoverflow.com/a/14236954/560648"><em>@VisioN</em>'s adapted code</a> will also add this space-banning support to copy-paste operations, whilst still avoiding text-replacement-on-<code>keyup</code> handlers that affect your textbox value whilst your caret is still active within it.</p> <p>So here's the final code:</p> <pre><code>$(function() { // "Ban" spaces in username field $("input#Username").on({ // When a new character was typed in keydown: function(e) { // 32 - ASCII for Space; // `return false` cancels the keypress if (e.which === 32) return false; }, // When spaces managed to "sneak in" via copy/paste change: function() { // Regex-remove all spaces in the final value this.value = this.value.replace(/\s/g, ""); } // Notice: value replacement only in events // that already involve the textbox losing // losing focus, else caret position gets // mangled. });​​​​​ }); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload