Search code examples
javascripthtmldefault-value

Reset HTML element to default value with JavaScript


Problem:

I am wondering if there is a similar function that allows resetting a text to its default value like there is for the value attribute.

HTML:

<input type="range" class="custom-range" name="studyslider" min="1" max="100" step="1" value="50" oninput="sliderChange(this)" onchange="sliderChange(this)">
<output class="badge badge-light badge-width mt-4 mb-3" name="studyslider-output">50</output>

JavaScript:

// Resetting the value for <input>
const slider = node.querySelector(".custom-range");
slider.value = slider.defaultValue;

// Resetting the value for <output>
const sliderOutput = node.querySelector("output");
sliderOutput.innerHTML = "50";

Desired output:

To pick up the value inside <output> and resetting it every time an answer is submitted, similar to that of defaultValue for <input>.


Solution

  • you are trying to assign the value of slider.defaultValue to sliderOutput.innerHTML, Why not just do this ?

    // Resetting the value for <input> const slider = node.querySelector(".custom-range"); slider.value = slider.defaultValue;

    // Resetting the value for <output> const sliderOutput = node.querySelector("output"); sliderOutput.innerHTML = slider.defaultValue;