Daniel Yantis Daniel Yantis - 5 months ago 24
Javascript Question

Using JavaScript want to auto update output value of a range slider with multiple sliders on the form

I would like to have 1 script handle multiple id's. The below example works great with the paint id output field, but how to pass the id to the script so that instead of #paint i can use the id that sent for the function?

in head

function outputUpdate(num) {
document.querySelector('#paint').value = num;
}


in form

<fieldset>
<legend><h3>Paint / Body</h3></legend>
<output for="paint" id="paint">0</output>
<input id="paint" type="range" min="0" max="10" value="0" step="1" list="0-10" oninput="outputUpdate(value)">
</fieldset>
<fieldset>
<legend><h3>Wheels</h3></legend>
<output for="wheels" id="wheels">0</output>
<input id="wheels" type="range" min="0" max="5" value="0" step="1" list="0-5" oninput="outputUpdate(value)">
</fieldset>
<fieldset>
<legend><h3>Body Mods</h3></legend>
<output for="bodymods" id="bodymods">0</output>
<input id="bodymods" type="range" min="0" max="15" value="0" step="1" list="0-15" oninput="outputUpdate(value)">
</fieldset>
<fieldset>
<legend><h3>Engine</h3></legend>
<output for="engine" id="engine">0</output>
<input id="engine" type="range" min="0" max="10" value="0" step="1" list="0-10" oninput="outputUpdate(value)">
Closed: <input type="checkbox" name="engine-closed" value="0" />
</fieldset>


like to use something like this:

function outputUpdate(id, num) {
document.querySelector(id).value = num;
}

Answer

Update your javascript function to accept a second parameter

function outputUpdate(num, selector) {
   document.querySelector('#'+selector).value = num;
}

And call this from your html code like

<input id="paint" type="range" min="0" max="10" value="0" step="1" list="0-10" oninput="outputUpdate(value, 'paint')">

<input id="wheels" type="range" min="0" max="5" value="0" step="1" list="0-5" oninput="outputUpdate(value, 'wheels')">

etc.