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 fine. (the elements have dynamic classes, for ex. “hide-if-123”)
However, I would also like to hide relevant elements when the page loads.
Should I use a different function (instead of “change”)?
Or maybe put the code outside the function as well, so it executes on load and on change?
I tried this:
$('.select').parent().siblings('.hide-if-' + $('.select').val()).hide();
but it doesn’t work. I presume I have this part $('.select').val() wrong.
It is important that it gets the value of the same select field as the "select" in the beginning of the line. I also tried:
$('.select').parent().siblings('.hide-if-' + $(this).val()).hide();
but still no luck.
Thanks a lot for your help!
In order to execute your change logic when the page is loaded you can simply trigger the
changeevent.