Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to link a Range and a Numerical HTML input?

Is there a way to link the values of a <input type="range"> and an <input type="number">?

I would like to make changes to either the slider or to the numerical input and have both fields be updated. For some reason I have only been able to get an undefined value from the range element as of yet.

Here is my current JavaScript and HTML for this part of the document:

function updateTextInput1(val) {
  alert(val);
  document.getElementById('num1').value = val;
}
<input class="inputRange" type="range" min="0" max="100" onchange="updateTextInput1(this.val)" />
<input class="inputNumber" id="num1" min="0" max="100" type="number" value="0" />
like image 342
veryRandomMe Avatar asked Dec 18 '15 17:12

veryRandomMe


People also ask

Can an input have multiple types in HTML?

The multiple attribute is a boolean attribute. When present, it specifies that the user is allowed to enter more than one value in the <input> element. Note: The multiple attribute works with the following input types: email, and file.

How do I restrict HTML inputs to numeric values?

To limit an HTML input box to accept numeric input, use the <input type="number">. With this, you will get a numeric input field. After limiting the input box to number, if a user enters text and press submit button, then the following can be seen “Please enter a number.”


1 Answers

It's not working because updateTextInput1(this.val) should be updateTextInput1(this.value):

function updateTextInput1(val) {
  document.getElementById('num1').value = val;
}
<input class="inputRange" type="range" min="0" max="100" onchange="updateTextInput1(this.value)" />
<input class="inputNumber" id="num1" min="0" max="100" type="number" value="0" />

However, I'd suggest using unobtrusive JavaScript, though.

Just attach an input event to each element. In doing so, both elements will be in sync.

var range = document.querySelector('.inputRange');
var field = document.getElementById('num1');

range.addEventListener('input', function (e) {
  field.value = e.target.value;
});
field.addEventListener('input', function (e) {
  range.value = e.target.value;
});
<input class="inputRange" type="range" min="0" max="100" value="0" />
<input class="inputNumber" id="num1" min="0" max="100" type="number" value="0" />

Or you could use a more compact approach and select the sibling element:

document.querySelector('.inputRange').addEventListener('input', updateValue);
document.getElementById('num1').addEventListener('input', updateValue);

function updateValue (e) {
  var sibling = e.target.previousElementSibling || e.target.nextElementSibling;
  sibling.value = e.target.value;
}
<input class="inputRange" type="range" min="0" max="100" value="0"/>
<input class="inputNumber" id="num1" min="0" max="100" type="number" value="0" />
like image 191
Josh Crozier Avatar answered Sep 22 '22 06:09

Josh Crozier