简体   繁体   中英

Groovy Loop through SELECT and amend checkboxes

I have a select with three options, and multiple checkboxes.

<select id="mySelect">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>

<div>
<input id="checkbox1" type="checkbox" value="checkbox1">Checkbox 1
<input id="checkbox2" type="checkbox" value="checkbox2">Checkbox 2
<input id="checkbox3" type="checkbox" value="checkbox3">Checkbox 3
</div>

I'd like to change which checkboxes are visible based on the options that are selected in the select, using Groovy.

For example, if option1 is selected, only checkbox1 should show. If option1 and option3 are selected, checkbox1 and checkbox3 should show. The ID's won't always match (eg. option1 might show checkbox3 rather than checkbox1 if I wanted it to).

I presume I'm going to need some kind of mapping table for the options against the checkboxes, and then loop through the options and show the correct checkboxes.

I can do it with multiple if statements (if mySelect equals option1 then show X etc) but multiple if statements will be very ugly. If there is a better way of doing this with a loop I'd appreciate the guidance.

Thanks

You can do like this:-

HTML - add a class to the checkboxes wrapper

<div class="checkbox-container">
    <input id="checkbox1" type="checkbox" value="checkbox1">Checkbox 1
    <input id="checkbox2" type="checkbox" value="checkbox2">Checkbox 2
    <input id="checkbox3" type="checkbox" value="checkbox3">Checkbox 3
</div>

JS

const selectEelement = document.getElementById("mySelect");

selectEelement.addEventListener('change', function() {
    var selectedValue = selectEelement.options[e.selectedIndex].value;
    var checkboxId = `checkbox${selectedValue.substr(selectedValue.length-1)}`;

    // First hide all the checkboxes
    document.querySelector('.checkbox-container').style.visibility = "hidden";

    // then show a particular checkbox
    document.getElementById(checkboxId).style.visibility = "visible";
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM