I'm don't know much about javascript, but and slowly learning through using other people's code. The below code I'm using is quite repetitive, with the only variance being the ID names. I feel like someone will know (and hopefully show) me how to do this show/hide function better.
$('#C7-Drawer-Shelf-Combo').on('change', function () {
if (this.value) {
$(".under-drawer-bench").show();
} else {
$(".under-drawer-bench").hide();
}
});
$('#T7-Drawer-Shelf-Combo').on('change', function () {
if (this.value) {
$(".under-drawer-bench").show();
} else {
$(".under-drawer-bench").hide();
}
});
$('#C11-Drawer-Shelf-Combo').on('change', function () {
if (this.value) {
$(".under-drawer-bench").show();
} else {
$(".under-drawer-bench").hide();
}
});
$('#T11-Drawer-Shelf-Combo').on('change', function () {
if (this.value) {
$(".under-drawer-bench").show();
} else {
$(".under-drawer-bench").hide();
}
});
$('#14X-Drawer-Shelf-Combo').on('change', function () {
if (this.value) {
$(".under-drawer-bench").show();
} else {
$(".under-drawer-bench").hide();
}
});
$('#17X-Drawer-Shelf-Combo').on('change', function () {
if (this.value) {
$(".under-drawer-bench").show();
} else {
$(".under-drawer-bench").hide();
}
});
2 Answers 2
You can change the selector to select all items at once.
First option: select all ids comma separated:
$('#C7-Drawer-Shelf-Combo,#T7-Drawer-Shelf-Combo,#C11-Drawer-Shelf-Combo').on('change', function () {
if (this.value) {
$(".under-drawer-bench").show();
} else {
$(".under-drawer-bench").hide();
}
});
Second option (prefered): use a css class. Add a specific css class to all those items, and use this class in the selector:
<select id="#C7-Drawer-Shelf-Combo" class="custom-class">....</select>
<select id="#T7-Drawer-Shelf-Combo" class="custom-class">....</select>
<select id="#C11-Drawer-Shelf-Combo" class="custom-class">....</select>
$('.custom-class').on('change', function () {
if (this.value) {
$(".under-drawer-bench").show();
} else {
$(".under-drawer-bench").hide();
}
});
-
\$\begingroup\$ Thank you, I ended up using your first option, with a little edit - I used the ID phrase that @aloisdg wrote "[id$='-Drawer-Shelf-Combo']" to save having to type all IDs out. \$\endgroup\$Liv Strawbridge– Liv Strawbridge2021年07月06日 00:22:22 +00:00Commented Jul 6, 2021 at 0:22
You can target all element ending with [id$='-Drawer-Shelf-Combo']
. Use toggle
to show/hide.
$("[id$='-Drawer-Shelf-Combo']").on('change', function () {
$(".under-drawer-bench").toggle();
});
Withtout the HTML/CSS I cant test it though.
-
\$\begingroup\$ Thanks for your comment, I needed to keep it as show/hide instead of toggle as I didn't want it to toggle off in case if the user changes their mind and selects a different dropdown option, but I used your ID phrase as that saved me having to type all the IDs out (see comment on answer). \$\endgroup\$Liv Strawbridge– Liv Strawbridge2021年07月06日 00:28:18 +00:00Commented Jul 6, 2021 at 0:28
*-Under-Drawer-Bench
. \$\endgroup\$