I am trying to re-create the functionality of https://chriscoyier.net/ where you have a form with radio buttons, and as you click a radio button, the text changes.
What I started with was:
window.onload=function() {
document.getElementById("hidden_elements").style.display="none";
// attach the click event handler to the radio buttons
var radios = document.forms[0].elements["group1"];
for (var i = [0]; i < radios.length; i++)
radios[i].onclick=radioClicked;
}
function radioClicked() {
if (this.value == "two") {
document.getElementById("hidden_elements").style.display="block";
} else {
document.getElementById("hidden_elements").style.display="none";
}
}
<form id="picker" method="post" action="">
Item 1: <input type="radio" name="group1" value="one" />
Item 2: <input type="radio" name="group1" value="two" />
Item 3: <input type="radio" name="group1" value="three" /><br />
<br />
<div id="hidden_elements">
Input 1: <input type="text" id="intext" />
Input 2: <input type="text" id="intext2" />
Input 3: <input type="text" id="intext3" /><br /><br />
</div>
<input type="submit" id="submitbutton" value="Send form" />
</form>
This allows me hide or display the div with id="hidden_elements" if input number 2 is selected.
What I want to do is hide or display the individual elements of "hidden_elements" based on the input 1, 2 or 3.
I tried changing the "hidden_elements" attributes to:
<div id="hidden_elements">
Input 1: <input type="text" name="one" />
Input 2: <input type="text" name="two" />
Input 3: <input type="text" name="three" /><br /><br />
</div>
and JS to:
var hide = document.getElementById("hidden_elements");
for (var i = [0]; i < hide.length; i++)
hide[i].style.display = "none";
function radioClicked() {
document.getElementsByName(this.value).style.display = "block"
}
But that doesn't work either.
I've tried a less appealing approach using if/else statements, but that too doesn't work.
<div id="paragraphs">
<div id="hidden_element" name="one">Paragraph 1 </div>
<div id="hidden_element" name="two">Paragraph 2 </div>
<div id="hidden_element" name="three">Paragraph 3 </div>
</div>
function radioClicked() {
if (this.value == "one") {
document.getElementById("hidden_element_one").style.display="block";
} else if (this.value == "two") {
document.getElementById("hidden_element_two").style.display="block";
} else if (this.value == "three") {
document.getElementById("hidden_element_three").style.display="block";
}
}
I've tried a few more approaches but the behaviour isn't what I want. Any idea how I can change the display from "none" to "block" based on the selected radio-button? (I know you can do it with JQuery but I'm trying to learn Javascript)