Reputation: 3
I want to have a dependent numeric input.
This numeric input depends on a select box that creates a specific numeric range for the input by selecting each option.
For example:
if we select option2, the numeric input will be min = 20 and max = 50!, if we select option3, the numeric input will be min = 10 and max = 30!. How can such a feature be created?
Here's what I've tried:
<form>
<select id="selbox">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
</select>
<input type="number" id="num">
<button>click</button>
</form>
Upvotes: 0
Views: 52
Reputation: 121
You can achieve this in JavaScript by adding a change EventListener to the select
tag which will help you extract the range values selected. Then you set those as min
and max
attributes for the input
.
const select = document.querySelector("#selbox");
const textBox = document.querySelector("#num");
select.addEventListener("change", setRangeForInput);
function setRangeForInput() {
const [rangeMin, rangeMax] = select.value.split('-'); //this is ES6 destructuring syntax
textBox.setAttribute("min", rangeMin);
textBox.setAttribute("max", rangeMax);
}
<form>
<select id="selbox">
<option value="20-40">option1</option>
<option value="30-50">option2</option>
<option value="3-7">option3</option>
</select>
<input type="number" id="num">
<button>click</button>
</form>
Upvotes: 1