Reputation: 569
I have a form that conditionally disables select field options based on the value from a previous select field. In my example, salt is offered for sale at different weights, with weights determined by the type of salt.
My form select looks like this:
<select id="salt_type" class="form-control" name="salt_type">
<option value="null" selected disabled>Select a salt type</option>
<option value="block-salt">Block Salt</option>
<option value="tablet-salt">Tablet Salt</option>
<option value="granular-salt">Granular Salt</option>
</select>
<select id="pack_weight" class="form-control" name="pack_weight">
<option value="null" selected disabled>Select a weight</option>
<option class="hide-if-tablet-salt hide-if-granular-salt" value="8kg">8kg</option>
<option class="hide-if-block-salt" value="10kg">10kg</option>
<option class="hide-if-block-salt hide-if-granular-salt" value="25kg">25kg</option>
</select>
My JS:
$('#salt_type').bind('change', function() {
var bool = ($(this).find(':selected').val() === 'block-salt') ? true : false;
$('.hide-if-block-salt').prop('disabled', bool);
var bool2 = ($(this).find(':selected').val() === 'granular-salt') ? true : false;
$('.hide-if-granular-salt').prop('disabled', bool2);
var bool3 = ($(this).find(':selected').val() === 'tablet-salt') ? true : false;
$('.hide-if-tablet-salt').prop('disabled', bool3);
});
It works if there's only one limiting class, but if there are two, the option isn't always disabled. It doesn't even seem to be consistent in failing to disable the first, or the last class.
I tried using classList.contains:
$('#fw_salt_type').bind('change', function() {
var bool = ($(this).find(':selected').val() === 'block-salt') ? true : false;
$('.pack-weight-option').classList.contains('hide-if-block-salt').prop('disabled', bool);
});
But I get a 'classlist not defined' error. Any help appreciated.
Upvotes: 0
Views: 40
Reputation: 599
Suggest to use non-negative class name for less confused
<option class="show-if-block-salt" value="8kg">8kg</option>
<option class="show-if-tablet-salt show-if-granular-salt" value="10kg">10kg</option>
<option class="show-if-tablet-salt" value="25kg">25kg</option>
Then on salt option change, enable only weight options with show class.
$('#salt_type').bind('change', function() {
var value = $(this).find(':selected').val();
$('#pack_weight option').each(function() {
$(this).prop('disabled', !$(this).hasClass(`show-if-${ value }`));
});
});
https://codesandbox.io/s/cranky-easley-vpcvh
Upvotes: 1