JS beginner here so any help is appreciated.
I am trying to get show/hide DIV based on JS.
I am using the following:
HTML
<Select id="single-option-selector-product-template-0">
<option value="White">White</option>
<option value="Navy">Navy</option>
<option value="Heather Ash">Heather Ash</option>
<option value="Heather Grey">Heather Grey</option>
</Select>
<div id="White" class="colours" style="display:none"> White </div>
<div id="Navy" class="colours" style="display:none"> Navy </div>
<div id="Heather Ash" class="colours" style="display:none">Heather Ash </div>
<div id="Heather Grey" class="colours" style="display:none"> Heather Grey </div>
JS
jQuery(function() {
jQuery('#single-option-selector-product-template-0').change(function(){
$('.colours').hide();
$('#' + $(this).val()).show();
});
});
Single words option like White and Navy are working fine but not those with 2 or more words like Heather Ash and Heather Grey. The option values are created when I create product in Shopify.
3
Answers
You cannot use
id
values that has whitespace separated words. You can join them using underscore and use the same value as avalue
of your<option>
element:If you can you should avoid
id
values with spaces in them as they can be hard to work with. However, if you have no control over theid
values in your HTML, you can use$.escapeSelector
(available since jQuery 3.0) to work around the fact that you have a space in yourid
value which would otherwise cause (for example)#Heather Ash
to look for anAsh
element under#Heather
.