0

I am making a form field where I would like to do a simple show-hide to display div's on a radio button.

<form id="basic" name="basic"> <label><input name="formelement" type="radio" value="yes" /> Yes </label> <label><input name="formelement" type="radio" value="no" /> No </label> <div id="yes" style="display: none;"> This is the div that displays that shows when 'Yes' is selected. </div> <div id="no" style="display: none;"> This is the div that displays that shows when 'No' is selected. </div> </form> 

I have played with some various javascript's I have found online and have achieved not a lot of success as most of them online manage to show-hide one div. Getting the 'yes' to hide when 'no' is selected and vice-versa is the tricky part. If anyone could provide some assistance that would be really appreciated!

2
  • 1
    you may want to use JQuery. Take a walk-through at their tutorial, you will be able to do that with much ease w3schools.com/jquery/default.asp Commented Jul 5, 2012 at 4:10
  • 1
    W3Schools is not regarded as one of the best places to learn JavaScript / jQuery (see W3Fools.com). A well-respected alternative for JavaScript is MDC's JavaScript Guide (developer.mozilla.org/en/JavaScript) . For jQuery, check out jQuery's documentation (docs.jquery.com/Main_Page) Commented Jul 5, 2012 at 4:17

3 Answers 3

3

Just paste these code between head tags

<script type="text/javascript"> window.onload=function(){ var el1 = document.getElementsByName('formelement')[0]; var el2 = document.getElementsByName('formelement')[1]; el1.onchange=function(){ var show=el1.value; var hide=el2.value; document.getElementById(show).style.display='block'; document.getElementById(hide).style.display='none'; } el2.onchange=function(){ var show=el2.value; var hide=el1.value; document.getElementById(show).style.display='block'; document.getElementById(hide).style.display='none'; } } </script> 

DEMO.

Sign up to request clarification or add additional context in comments.

Comments

0

The below is assuming value of radio is same as id of the div..

function getRadioVal(name){ var oRadio = document.forms[0].elements[name]; for(var i = 0; i < oRadio.length; i++) if(oRadio[i].checked) return oRadio[i].value; return ''; } //hide both divs.. document.getElementById("yes").style.display = "none"; document.getElementById("no").style.display = "none"; //show only one of them.. document.getElementById(getRadioVal("formelement")) = "block"; 

Dealing with javascript without any libraries is a pain when things get complex, I would recommend libraries such as jQuery

Comments

0

this is what you want

How can I check whether a radio button is selected with JavaScript?

assign onclick event and you are good to go.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.