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!

Brandrally
  • 803
  • 3
  • 14
  • 24
  • 1
    you may want to use JQuery. Take a walk-through at their tutorial, you will be able to do that with much ease http://www.w3schools.com/jquery/default.asp – Hoàng Long Jul 05 '12 at 04:10
  • 1
    W3Schools is not regarded as one of the best places to learn JavaScript / jQuery (see http://W3Fools.com). A well-respected alternative for JavaScript is MDC's JavaScript Guide (http://developer.mozilla.org/en/JavaScript) . For jQuery, check out jQuery's documentation (http://docs.jquery.com/Main_Page) – N30 Jul 05 '12 at 04:17

3 Answers3

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.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
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

UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
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.

Community
  • 1
  • 1
N30
  • 3,463
  • 4
  • 34
  • 43