Skip to content
Advertisement

Change the value of input based on options selected, but for multiple sets

I have a set of input/options:

<input type="checkbox" id="Devices001Master" class="Metals" value="Steel" onchange="ReDraw()">
<select id="Devices001" onchange="Devices001func()">
    <option value="Steel">Steel</option>
    <option value="Steel_1">Steel 1</option>
    <option value="Steel_2">Steel 2</option>
    <option value="Steel_3">Steel 3</option>
    <option value="Steel_4">Steel 4</option>
    <option value="Steel_5">Steel 5</option>
</select>

I’m able to, onchange, change the value of the input based on what’s being selected in the options. Followed by my redraw function that works exactly as intended. This works fine for 1 set at a time:

function Devices001func(){
    let Devices001Master = document.getElementById("Devices001Master");
    let Devices001 = document.getElementById("Devices001");
    Devices001Master.value = Devices001.value;
ReDraw();
};

My problem: Say I have something like 100 sets of input/options all with different types of “Metals”. I could reproduce my 6-line “Devices001func()” for each of the 100 sets but that’s 600 lines. I would gladly appreciate anyone who can point me to a vanilla JS approach to take here.

Cheers!

Advertisement

Answer

You can make use of event bubbling:

document.body.addEventListener('change', event => {
    const masterElement = document.getElementById(event.target.id + 'Master');

    if (masterElement !== null) {
        masterElement.value = event.target.value;
        ReDraw();
    };
});
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement