Reputation: 4096
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/
Upvotes: 3
Views: 3707
Reputation: 13967
You want to capture the onkeydown
event:
function doIt(e)
{
var e = e || event;
if (e.keyCode == 32) return false; // 32 is the keycode for the spacebar
}
window.onload = function(){
var inp = document.getElementById("inputText");
inp.onkeydown = doIt;
};
Note that they will still be able to paste spaces into the input, so you'll have to handle that as well.
To handle pasting, it's as simple as: http://jsfiddle.net/djSnL/7/
function pasteIt(e)
{
var e = e || event;
this.value = this.value.replace(/\s/g,'');
}
With both, you'll get the desired effect.
I'm not 100% certain, but I believe only webkit browsers will let you know what the data is before it's pasted: http://jsfiddle.net/djSnL/8/
function pasteIt(e)
{
var e = e || event;
var data = e.clipboardData.getData("text/plain");
if (data.match(/\s/g)) return false;
}
Upvotes: 2
Reputation: 4096
Okay, I think I got it, using jQuery. Thanks for all the help!
// Bind Events
function bindEvents()
{
$(inputText).bind('keydown paste', checkForSpaces);
}
// Check For Spaces
function checkForSpaces()
{
if (event.type == "keydown" && event.which == 32) {return false;}
if (event.type == "paste" && event.clipboardData.getData('text/plain').indexOf(" ") != -1) {return false;}
}
Upvotes: 1