I have a text input that I don't want spaces in. If someone types a space or pastes text with a space, I would like to change the text back to what it was before the space was inputted AND also keep the caret position the same. Maybe there is an easier way to do this, but I can't figure it out.
This is what I have so far:
<html><head><title>Test</title></head><body>
<input type=text id="inputText" value="testValue" onInput=doIt(this);>
</body></html>
And the javascript that would be included (I used jsFiddle):
var editedValue = "testValue";
// alert(editedValue);
function doIt(that)
{
var caretPos = that.selectionStart;
if (that.value.indexOf(" ") != -1)
{
that.value = editedValue;
// alert(caretPos);
that.selectionStart = caretPos;
}
else
{
editedValue = that.value;
}
}
It seems to all work, except for, if the caret is in the middle of the text, and you type or paste spaces, the caret does not return to the original position.
Can anyone help me figure this out? Or show me an entirely new/easier/simpler way to not allow spaces typed or pasted into a text input?
Here is the jsfiddle I was trying it with if it helps: http://jsfiddle.net/djSnL/4/