There is only one text field on a HTML form. Users input some text, press Enter, submit the form, and the form is reloaded. The main use is barcode reading. I use the following code to set the focus to the text field:
<script language="javascript">
<!--
document.getElementById("#{id}").focus()
//-->
</script>
It works most of the time (if nobody touches the screen/mouse/keyboard).
However, when the user click somewhere outside the field within the browser window (the white empty space), the cursor is gone. One a single field HTML form, how can I prevent the cursor from getting lost? Or, how to re-focus the cursor inside the field after the cursor is lost? thx!
You can hook the
blur
event and refocus the field again. There are very few use cases for doing this, but it sounds like yours may be one of them. Note that you'll probably have to schedule the re-focus viasetTimeout
or similar, you won't be able to do it within theblur
handler itself.When doing this without affecting the markup, this is easiest if you use a library like Prototype, jQuery, Closure, etc., but you can do it without them (of course), you just have to handle browser differences yourself. For instance, using Prototype:
If you don't mind affecting the markup, you can use the
onblur
attribute. For instance, this works on IE, Firefox, and Chrome at least (probably others):HTML:
Script:
Darin's answer is right, but doesn't work in Firefox. If you want to steal focus back in Firefox too, you have to delay it until after the event:
Or, better, assigned from JavaScript:
But, I would strongly advise you not to do this. Clicking outside a text box to remove focus from that text box is perfectly normal browser behaviour, which can be of legitimate use (eg. to set search point for ctrl-F, or start a drag-selection, etc). There's very unlikely to be a good reason to mess with this expected behaviour.