Skip to content

Instantly share code, notes, and snippets.

@lenrsmith
Created June 22, 2014 16:14
Show Gist options
  • Save lenrsmith/279bf2c5420c4246b579 to your computer and use it in GitHub Desktop.
Save lenrsmith/279bf2c5420c4246b579 to your computer and use it in GitHub Desktop.
Keep focus on an input box on an HTML form
/*
The following is the only way I could find to solve an annoying problem
I was having on an HTML Form. I needed to add items from an input box to a
multiple select control. I wanted to use the change event instead of a button
to speed up the process. Everytime the entry was loaded into the select, the
select control received focus requiring the user to tab or click back into the
input box. I tried to use the focus event in multiple combinations and the
following finally worked.
#new_item is an input that adds new items to a multiple select box
*/
var focusing = false
$('#new_item').blur(function(e){
if(focusing){
setTimeout(function(){
$('#new_item').focus();
}, 5);
focusing = false;
}
});
$('#new_item').on('change',function(e){
$('#select').append($("<option></option>").attr("value", $('#new_item').val()).text($('#new_item').val()));
$('#new_item').val('');
focusingNewRegion = true;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment