I created 2 input, one is Radio Button, and one is Dropdown. I want user to click on radio button and it will select the option in the dropdown with the same value.
How can I do this with JS, not using Jquery?
Please help me with this.
Thank you!
My sample code:
<p class="line-item-property__field">
<label>Color</label><br>
<input type="radio" name="color" value="1"> <span>1</span><br>
<input type="radio" name="color" value="2"> <span>2</span><br>
<input type="radio" name="color" value="3"> <span>3</span><br>
</p>
<p class="line-item-property__field">
<label>Color</label><br>
<select id="your-name" name="dropdown-color">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</p>
2
Answers
Yes you can add the event listeners to the properties in the radio button and for that event you can update the value of the dropdown values correspondingly.
eg: you can do like:
also please add the id as dropdown-color for the dropdown select list as
Hope this is what you need.
Use event delegation. This will allow you to add one listener to a parent element of the radio buttons to "catch" events from them as they bubble up the DOM.
The listener will call a function. First it will check that the event from the element that fired it is one of the radio buttons. Second it will assign that element’s value as the select element’s value.
(In this example I’ve modified your sample markup slightly to use a
fieldset
element, and properinput
labelling, which is perhaps more in line with the UI you’re trying to achieve.)Additional documentation
closest
querySelector
addEventListener
Event target