I'm currently using focusout on a specific form element in order to know when a user has tabbed onward or clicked on a different field.
I need to know this because an ajax call launch immediately after this and populates several different fields (e.g. Enter a valid zip code, it searches a db and comes back with city).
Now, my question, the ajax call receives an html response and on loading it, causes the form to lose its current focus.
I need a way to save that focus and reinstate it after the ajax call.
So far, I've gotten the navigation to kind of work. It breaks a lot, and also interferes with the loading of other things on the page (e.g. dialog windows). So, I figure there has to be a better way to do it, which is why I'm here. Let me know if you need more information. Code is below.
All the best!
$('.DZipCode').focusout(function () {
var ZipCode = $('.DZipCode').val();
$.ajax({ // create an AJAX call...
async: false,
type: "POST", // GET or POST
url: "/Home/SelectZipCodeDataDestination", // the file to call`
data: { zipCode: ZipCode },
success: function (response) { // on success..
$(":input").focus(function() {
var prevFocus;
prevFocus = $(this).attr("id");
$('#quotetab').html(response);
$('#'+prevFocus).focus();
// });
} // end of success
}); // end of .ajax
});
The easiest way I can think of is to set a flag when a key is pressed, then just check the flag whenever you need to know.
var tabPressed = false;
$('input[type="text"], textarea')
.keydown(function(e) {
var keyCode = e.keyCode || e.which;
tabPressed = (keyCode==9) ? true : false;
})
.focus(function() {
tabPressed = false;
});
Then you can do
if(tabPressed) {
//some stuff
}
in your ajax success callback (or wherever).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With