How do I use the dropdown value of a select box to load a page to hide an element using JQuery?
I am hiding some elements based on the current value of a select field with the following JQuery:
$('.select').change(function() {
$(this).parent().siblings('*[class*=hide-if-]').show();
$(this).parent().siblings('.hide-if-' + $(this).val()).hide();
});
And it works great. (elements have dynamic classes like "hide-if-123")
However, I would also like to hide the relevant elements on page load. Should I be using a different function (instead of "change")?
Or maybe put the code outside of the function so that it gets executed on load and on change? I've tried this:
$('.select').parent().siblings('.hide-if-' + $('.select').val()).hide();
but that won't work. I am guessing this part $('.select').val()
is wrong.
It is important that it gets the value of the same select box as "select"
at the beginning of the line. I've also tried:
$('.select').parent().siblings('.hide-if-' + $(this).val()).hide();
but still no luck.
Many thanks for your help!
source to share
You can simply run the change handler you already created:
$('.select').change(function() {
$(this).parent().siblings('*[class*=hide-if-]').show();
$(this).parent().siblings('.hide-if-' + $(this).val()).hide();
}).change();
Calling .change()
without parameters is equivalent .trigger('change')
.
Although I said I don't understand why your code is:
$('.select').parent().siblings('.hide-if-' + $('.select').val()).hide();
won't work - do all the elements exist when the page is loaded first? And is the above line included in the finished document and / or at the end of the body after the items in question)?
source to share