Try this script:
But before that, the form
‘s method
should remain as GET
. And in the form
markup/HTML, remove the onchange="this.form.submit()"
from all the checkbox
fields. Then add a standard submit button to the form; example:
<input type="submit" value="Go" />
[EDIT] The submit button is not necessary. I’ve updated the script so that when selecting a filter (i.e. “checking” a checkbox
), the AJAX request is fired automatically.
Next, make sure to assign a unique ID to the posts/result div
or container. For this example, the ID is my-unique-ID
. (This container must not include the filter form.)
Now here’s the script:
<script>
jQuery( function( $ ){
function ajaxFilter() {
var $form = $( 'form#filter' );
// Disable the submit button and then remove its focus.
$form.find( ':submit' ).prop( 'disabled', true ).blur();
// Make sure to change my-unique-ID to the correct value.
$( '#my-unique-ID' ).load(
$form.attr( 'action' ) + ' #my-unique-ID',
$form.serialize(),
function(){
// Enable the submit button once AJAX is complete.
$form.find( ':submit' ).prop( 'disabled', false );
}
);
}
// Run the AJAX request upon submitting the form.
$( 'form#filter' ).on( 'submit', function( e ){
e.preventDefault();
ajaxFilter();
} );
// Run the AJAX request upon selecting a filter; i.e. "checking" a checkbox.
$( ':checkbox', 'form#filter' ).on( 'change', function(){
ajaxFilter();
} );
} );
</script>
You can add the script after the posts/result container, or before the closing </body>
tag, or somewhere else that you think is appropriate (which means jQuery must have already been loaded).
Hope that helps, and just let me know if you need further assistance.