Show/Hide div with multiple radio buttons – JavaScript

In this post i would discuss, how to show only the div content associated with a particular radio button.

Lets say my html is like:

<form name='formname'>
	<input type='radio' name='levels' value='level1' onClick=\"get_radio_value(1);\" >
	<br>
	<input type='radio' name='levels' value='level2' onClick=\"get_radio_value(2);\" >
	<br>
	<input type='radio' name='levels' value='level3' onClick=\"get_radio_value(3);\" >
	<br>
	<input type='radio' name='levels' value='level4' onClick=\"get_radio_value(4);\" >
</form>

<br><br>

<div id='level1' style='display:none;'>
	Here is Level 1
</div>

<div id='level2' style='display:none;'>
	Here is Level 2
</div>

<div id='level3' style='display:none;'>
	Here is Level 3
</div>

<div id='level4' style='display:none;'>
	Here is Level 4
</div>

So in this case we have 4 radio buttons and 4 div’s and each radio button’s value corresponds to div’s id. It is using function get_radio_value():

function get_radio_value(val)
{
	val = val - 1;
	for (var i=0; i < document.formname.levels.length; i++){
		  if(i==val){
			document.formname.levels[i].checked = true;
		   }
	}
	for (var i=0; i < document.formname.levels.length; i++){
	   if (document.formname.levels[i].checked)
	      {
		      var rad_val = document.formname.levels[i].value;
		      document.getElementById(rad_val).style.display = "block";
	      }
	   else{
		var rad_val = document.formname.levels[i].value;
		document.getElementById(rad_val).style.display = "none";
	   }
   	}
}

———————————————————————————————————————————————

See Demo Below:

Tags: ,
Subscribe to Comments RSS Feed in this post

3 Responses

  1. Total score! Thanks, this was exactly what I needed.

  2. thanks a lot!! i needed the above, helped me a lot.

  3. Thank u i wanted exactly this …u made my day thanks a ton

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*