Reputation: 1
I have a task where I have to display seperate dropdown lists for each option in radio buttons. When I select a radio button (not selecting a radio button and then clicking on 'submit'. Just selecting(clicking on) a radio button), the corresponding dropdown list should be displayed in the side.
Upvotes: 0
Views: 3495
Reputation: 78
I made an example for you here.
The example is basically the following steps:
Mark up your HTML
<label>Radio 1</label>
<input type="radio" name="group" value="1" checked />
<label>Radio 2</label>
<input type="radio" name="group" value="2" />
<label>Radio 3</label>
<input type="radio" name="group" value="3" />
<div>
<select id="drop1">
<option>DropDown 1</option>
</select>
<select id="drop2" class="no-display">
<option>DropDown 2</option>
</select>
<select id="drop3" class="no-display">
<option>DropDown 3</option>
</select>
</div>
Add CSS
.no-display {display: none;}
Add event listeners to the radio buttons that call your drop-down selecting function
var radio_buttons = document.getElementsByName("group");
for (var i = 0; i < radio_buttons.length; i++) {
radio_buttons[i].addEventListener("change", setDropDown);
}
function setDropDown() {
setDropDownsForNoDisplay();
if (this.checked) {
setDropDownForDisplay(this.value);
}
}
Add helper functions that the drop-down selecting function uses
var dropdowns = document.getElementsByTagName("select");
function setDropDownsForNoDisplay() {
for (var i = 0; i < dropdowns.length; i++) {
dropdowns[i].classList.add("no-display");
}
}
function setDropDownForDisplay(x) {
if (x === "1") {
document.getElementById("drop1").classList.remove("no-display");
} else if (x === "2") {
document.getElementById("drop2").classList.remove("no-display");
} else if (x === "3") {
document.getElementById("drop3").classList.remove("no-display");
}
}
You could also use events ("onclick", "onchange") directly in the radio button markup instead of adding event listeners, but I prefer keeping my events separated from the markup.
Upvotes: 0
Reputation: 564
You want to listen to the on 'change' event, this is an example with jquery:
$('select').hide();
$('input').on('change', function(){
$('select').show();
})
I've dropped a working example into jsbin: https://jsbin.com/xohecizina/edit?html,js,output
Upvotes: 1