Daniel Yantis Daniel Yantis - 5 months ago 15
Javascript Question

Make another element visible/not visible based on checkbox value

I'm totally learning here! I'm still playing with JS.

When checkbox is altered I want the range slider to be inactive AND the output to be zero.



function outputUpdate(obj) {
obj.previousElementSibling.value = obj.value;
}

function handleClick(obj) {
obj.previousElementSibling.value = obj.value;
}

<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(this)">
<input type="checkbox" name="engine-closed" id="engine-closed" onclick='handleClick(this);' value="0" /><label for="engine-closed">Closed</label>
</fieldset>





I'm not sure how to make the range slider inactive / invisible on checkbox.
Then when unchecked make slider active / visible again.

Further, how to make the output zero when checkbox changes?

So far, with above code, slider works great and it updates output.
When checkbox checked the slider goes to zero as wanted, but not output.

edit: there are about 20 different form sliders with outputs. So it would be nice to use the id that called the function rather than declaring a var...

Answer

Here, with minimal changes to your code :)

function outputUpdate(obj) {
  obj.previousElementSibling.value = obj.value;
}

function handleClick(obj) {
  obj.previousElementSibling.value = obj.value;
  obj.previousElementSibling.disabled = (obj.checked) ? true : false;
}
<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(this)">
  <input type="checkbox" name="engine-closed" id="engine-closed" onclick='handleClick(this); outputUpdate(this.previousElementSibling);' value="0" />
  <label for="engine-closed">Closed</label>
</fieldset>

You can add the visibility toggle part if you want to.