For instance, suppose I have an HTML form like this:
<form role="search" method="get" id="searchform" action="" >
<!-- DIRECT SEARCH INPUT TO SEARCH STRING -->
<input type="text" value="" name="s" id="s" />
<input type="submit" id="searchsubmit" value="Search" />
<!-- DROPDOWN TO SELECT ONE CHOICE -->
<select name='country' id='country' class='postform' >
<option class="level-0" value="2">USA</option>
<option class="level-0" value="3">Canada</option>
<option class="level-0" value="4">Mexico</option>
<option class="level-0" value="5">Cuba</option>
</select>
<!-- CHECKBOXES TO SELECT MULTIPLE CHOICES -->
<div id="color">
<input type="checkbox" name="" value="21" />Beachfront
<input type="checkbox" name="" value="16" />TV
<input type="checkbox" name="" value="20" />Internet
<input type="checkbox" name="" value="17" />Pets Allowed
</div>
</form>
<div id="results"><!-- THE AJAX RESULTS GOES HERE --></div>
If I want to trigger an AJAX request whenever the user:
1) enters something in the search input box and clicks the search button
OR
2) selects an option from the dropdown menu
OR
3) checks one or more options from the checkboxes
The challenge lies in organizing my JavaScript code effectively to manage the user's selections across these different inputs. This includes considering not just the search term entered when clicking the search button, but also taking into account any previous choices made from the dropdown and checkboxes. Here is a snippet of what I've attempted so far:
jQuery(document).ready(function($){
// DISPLAY RESULTS IN #results DIV AFTER AJAX CALL
var $maincontent = $('#results');
// PROCESSING SEARCH INPUT
$('#searchsubmit').click(function(e){
e.preventDefault();
var searchval = $('#s').val();
$.post(
WPaAjax.ajaxurl,
{
action : 'ajax_search_action_do',
searchval : searchval
},
function( response ) {
$maincontent.empty();
$maincontent.append( response );
}
);
});
// PROCESSING COUNTRY SELECTION FROM DROPDOWN
$('#country').on('change', function() {
var countryval = this.value;
$maincontent.animate({ opacity : '0.1' })
$.post(
WPaAjax.ajaxurl,
{
action : 'ajax_search_action_do',
countryval : countryval
},
function( response ) {
$maincontent.empty();
$maincontent.append( response );
$maincontent.animate({ opacity : '1' })
}
);
return false;
});
// PROCESSING CHECKBOX SELECTIONS
$('#color input[type=checkbox]').click(function() {
if (this.checked) {
// handle checked state
}
else {
// do nothing
}
});
});
As you can see, the code is fragmented with separate functions for click events, changes, and checkbox handling. It would be beneficial to consolidate these checks into a more cohesive structure. Any suggestions on how to achieve this in JavaScript?
Your insights and ideas are appreciated.