kexxcream
kexxcream

Reputation: 5943

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>.

Upvotes: 0

Views: 6506

Answers (3)

naortor
naortor

Reputation: 2087

You could also use the native reset.

function sliderChange(e) {
  document.getElementById("output").value = document.getElementById("slider").value
}
<form>
  <input id="slider" 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" id="output">50</output>
<input type="reset" />
</form>

Upvotes: 0

minuteMed
minuteMed

Reputation: 887

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;

Upvotes: 1

NoOorZ24
NoOorZ24

Reputation: 3277

You can use data-X attribute:

<output data-default-value="50">50</output>

JS:

sliderOutput.innerHTML = sliderOutput.dataset.defaultValue

Upvotes: 2

Related Questions