The following code currently only generates a search query whenever a keyup event happens. This hasn't been a problem up until I started using webkit and it is now possible to clear the search field without pressing any keys (by clicking the "x" in the search field).
Is it possible to get the same function to fire whenever there is a change in the search box?
I have tried to replace .keyup with .change but that doesn't seem to produce any response when changes happen in the search box.
$('#search').keyup(function(e){
e.preventDefault();
search = $(this).val();
$.ajax({
url: '/lists.xml?search='+search,
dataType: "xml",
success: parseXML
});
});
Any help will be greatly appreciated!
EDIT: After some further research I've found this example.
The following code works in combina开发者_运维百科tion with the code above:
$('#search').click(function(e){
if($(this).val()==""){
e.preventDefault();
search = $(this).val();
$.ajax({
url: '/lists.xml?search='+search,
dataType: "xml",
success: parseXML
});
}
});
As far as I know, the change, blur, and focus events only occur when you take focus away from the textbox. Then they only check to see if the previous value was the same as the original.
So if the previous value was "" and you type "asdf", and click away from the text box to lose focus your function would fire. So now the value is "asdf". If you type "asdfeee", then erase the "eee" and take focus away the event won't fire, because the value will still equal "asdf".
I think the easiest solution here would be to leave the keyup event handler and simply add a click event handler that does the exact same thing to account for the WebKit behavior.
$('#search').blur(function(e) { // you may use `focus`
search = $(this).val();
if (search != null || search != '') {
$.ajax({
url: '/lists.xml?search=' + search,
dataType: "xml",
success: parseXML
});
}
});
After some further research I have come up with a solution to my own problem. In order to account for the webkit functionality I've added 2 event handlers as shown below. This isn't a perfect solution but it will do for now...
$('#search').keyup(function(e){
e.preventDefault();
search = $(this).val();
$.ajax({
url: '/lists.xml?search='+search,
dataType: "xml",
success: parseXML
});
});
$('#search').click(function(e){
if($(this).val()==""){
e.preventDefault();
search = $(this).val();
$.ajax({
url: '/lists.xml?search='+search,
dataType: "xml",
success: parseXML
});
}
});
This example helped in deriving the solution.
精彩评论