I thought this would be easy enough to do without seeking help, but I guess not. Adding the autofocus="true" tag works when the page initially loads but the text field loses focus if anyone clicks anywhere or opens a link. How do I force the field to keep focus?
Attach a click event listener on the document that focus's on the input box on click.
$(document).on("click", function()
{
$("yourInputIdHERE").focus();
}
$("#textbox").focus().on('blur', function() {
$(this).focus();
});
What you might want to try do, is attach an event handler to the blur
event. Once you capture it, you can simply trigger a focus event on the same element that lost focus in the first place.
$("input").on('blur',function(){
$(this).focus();
});
You might want to incorporate this with some form of validation so that once the user has entered the desired value, they will be able to leave the text field.
$("input").on('blur',function(){
var $this = $(this);
if ($this.val() == ''){
$this.focus();
showErrorMessage("Please enter a value");
}
});
If you don't implement some form of flag to enable/disable this behavior, you'll be locking the user into one field forever. There will be no (easy) way for them to move to a different area of the page.
Here is a small demo,
you'll notice that once the text field has focus, it will keep it until a value has been entered.
Handling all cases incase where some of the events are prevented from propagating till the document. Also handle the case where user switches tab and comes back.
$("#element").blur(function ()
{
$("#element").focus();
});
$(document).bind('keydown mousedown mouseup click',function ()
{
$("#element").focus();
});
Someone ask why you want to do that . the answer of-course is as a developers we need to deal we crazy demands by our clients :)
To the answer:
$(document).ready(function(){
$(document).click(function() { $("<THE-ELEMENT>").focus() });
});
In this case we add listener to all elements in the document :)