I’ve got a search UI with 1 – 5 input boxes that cause an ajax action on their change() event.
I’ve also got a ‘clear criteria’ button that should clear the input boxes when clicked. This works properly, but I’ve got one side effect that I’d like to be rid of.
If the user has entered data in a search input, but not left the field yet (ie change() hasn’t fired), and they click the ‘clear criteria’, this causes the change to fire and the ajax action occurs, then the input boxes clear.
I would like to stop the change() from happening if the user clicks on the ‘clear’ button.
I started writing the serachChangeHandler function, but haven’t figured out how identify if the inputbox is losing the focus to the .ui-clear button.
My question is: Can I tell in the change handler where the focus is going, or should I be approaching the problem from a different direction?
My relevant javascript looks like this:
function displayResults(data) {
$('.searchResults').html(data);
}
function searchChangeHandler(e) {
ajaxSearch();
}
function ajaxSearch() {
$('#selectedRecord').empty();
if (isSearchable()) {
var myForm = $('#searchForm');
$.post(myForm.URL, myForm.serialize(), displayResults);
} else {
$('.searchResults').empty();
}
}
function displayRecord(data) {
$('#selectedRecord').html(data);
}
function searchResultClick(e) {
$('.searchResult').removeClass('selected');
$(this).addClass('selected');
$.ajax({
url: this.id,
success: displayRecord,
dataType: "html"
});
}
function clearSearchClick() {
$('.search input:text').val("");
toggleClearButton(false);
$('.searchResults').empty();
$('.first').focus();
}
function isSearchable() {
var allCrit = "";
$('.search input:text').each(function () {
allCrit += $(this).val();
});
return allCrit !== "";
}
function toggleClearButton(callback) {
$('.ui-clear').toggleClass("clear-enabled", callback);
}
$(function () {
toggleClearButton(isSearchable());
$('.ui-clear').click(clearSearchClick);
$('.search input:text').focusout(searchChangeHandler);
$('.search input:text').keyup(function () { toggleClearButton(isSearchable()); });
$(document).keypress(function (event) {
if (event.which === 13) {
event.preventDefault();
ajaxSearch();
}
});
});
Just an idea using
setTimeoutUpdate: Also in your
$(document).keypress(...)you should callsearchChangeHandler()function instead of directly calling theajaxSearch()function becausesearchChangeHandler()is checking the input’s state and firingajaxSearch()after timeout.DEMO.