I need to only have 1 character at any time in an input field. The only way I can think of doing this is by having javascript keep everything in the box always selected and making the maximum input length 1 so that when I type something new, whatever was in there gets overwritten (since it is selected). That way I don’t have to use backspace or anything. So far I have only gotten as far as getting everything to select when you click in the box. I have this:
input type="text" id="txt1" size="30" maxlength="1" onkeyup="showHint(this.value)" onFocus="this.select()" onBlur="this.select()" onClick="SelectAll('txt1');" value="Click here, then press a key"/>
I have a couple different things going on in there to try to get it all selected (like the onFocus and the onBlur which don’t work). Any idea how I could keep everything in that box permanently selected? Or is there a better way altogether to keep a single character in the box?
How about this algorithm:
onfocus : select all content
onkeydown : delete all content
onkeyup : select all content
If you need the content to always be valid (i.e., you need to have one valid character in the box) you can do some extra validation on keyup and blur. If the value is valid save the valid value somewhere. If the value is not valid restore the previous valid value.
This would handle the situation where the key being pressed was something like the “tab” or “enter” buttons.
This logic may not work depending on what other actions you are taking on key presses, if any. But given the parameters in your question, this sounds like this will work.
Proof of concept code. Modify to your problem and tastes.