Reputation: 8759
I have a search form that I want to trigger an AJAX request, which contains both <input type="text">
and <select></select>
form elements.
I'd like to have the the AJAX request happen when someone starts typing, so I originally used:
$('#searchform').keyup(function() {
//GRAB TEXT FROM INPUT AND START AJAX
});
but now the form has drop downs, so to tackle that I changed it to:
$('#searchform').change(function() {
//GRAB VALUES FROM INPUT AND DROPDOWNS AND START AJAX
});
but that means it no longer starts the request whenever someone types anything in the <input type="text">
field until I modify something else.
Is it possible to have a function run based on whether the form "changes" or whether the input field is typed in? Should I write two functions or is there a selector that accomplishes this?
Upvotes: 0
Views: 2366
Reputation: 3695
If you delegate the event, you could have your function run on both events, like so:
$('#searchform').on('keyup change', function() {
//GRAB VALUES FROM INPUT AND DROPDOWNS AND START AJAX;
});
Just put a space between the events. Here is a quick and dirty example.
Upvotes: 4
Reputation: 6612
Write a function to call the ajax and pass the value as parameter
function foo(x) {
// ajax call with x
}
$('#searchform').keyup(function() {
//GRAB TEXT FROM INPUT AND START AJAX
foo($(this).val());
});
$('#searchform').change(function() {
//GRAB VALUES FROM INPUT AND DROPDOWNS AND START AJAX
foo($(this).val());
});
Upvotes: 1
Reputation: 4423
You will need to listen to both events, but you can simplify this by connecting both to a single callback, namely, update
.
var update = function() {
// Handle update to form.
};
$('#searchform').keyup(update);
$('#searchform').change(update);
Upvotes: 1