Skip to content

Instantly share code, notes, and snippets.

@jonschr
Last active April 5, 2023 05:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonschr/6bc52166db037e880772 to your computer and use it in GitHub Desktop.
Save jonschr/6bc52166db037e880772 to your computer and use it in GitHub Desktop.
Conditional logic with select2 (addon for the Beautiful taxonomy filters plugin)
jQuery(document).ready(function($) {
/**
* If the value is preselected (runs when the the doc is ready)
*/
// get the starting value of the field; empty means no selection is made and conditional fields should hide by default
var startingval = $('select#select-job-industry').val();
if ( startingval == '' ) {
// we have to use 'hide' rather than 'slidedown' as 'slidedown' doesn't actually hide anything on load
$('#beautiful-taxonomy-filters-tax-job-name').hide();
$('#beautiful-taxonomy-filters-tax-job-categories').hide();
}
if ( startingval == 'artisans' ) {
$('#beautiful-taxonomy-filters-tax-job-categories').hide();
}
if ( startingval == 'administrative-professionals' ) {
$('#beautiful-taxonomy-filters-tax-job-name').hide();
}
/**
* If it's changed while we're on the page...
*/
// watching for whenever the top box changes
$('select#select-job-industry').on('change', function() {
// clear the values of all conditional fields when the category changes
$( 'select#select-job-name' ).val('');
$( 'select#select-job-categories' ).val('');
// the content of the displayed span is separate from the select field, and we're going to clear that here as well and leave a placeholder
var defaulttext = '<span class="select2-selection__placeholder">All</span>';
$( '#select2-select-job-name-container' ).html( defaulttext );
$( '#select2-select-job-categories-container' ).html( defaulttext );
// get the value whenever the select field changes
var val = $(this).val();
if (val === '' ){
$( '#beautiful-taxonomy-filters-tax-job-name' ).hide();
$( '#beautiful-taxonomy-filters-tax-job-categories' ).hide();
}
if ( val === 'artisans' ){
$( '#beautiful-taxonomy-filters-tax-job-name' ).slideDown();
$( '#beautiful-taxonomy-filters-tax-job-categories' ).slideUp();
}
if ( val === 'administrative-professionals' ) {
$( '#beautiful-taxonomy-filters-tax-job-name' ).slideUp();
$( '#beautiful-taxonomy-filters-tax-job-categories' ).slideDown();
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment