Last active
April 5, 2023 05:09
-
-
Save jonschr/6bc52166db037e880772 to your computer and use it in GitHub Desktop.
Conditional logic with select2 (addon for the Beautiful taxonomy filters plugin)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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