Jump to content

radio button question


ssffcc

Recommended Posts

for dropdownlist, I can use these lines to retrieve the selected value:

	var countrylist=document.getElementById("country")    thecountry=countrylist.options[countrylist.selectedIndex].text

for radio buttons, I can only retrieve selected value by indexnumber:

  var gender  if (document.form1.gender[0].checked)  {    gender= "male"  }  else if (document.form1.gender[1].checked)  {    gender= "female"  }

if there are many radio buttons on a form, it will be hard to memorize all the value's index number, is there such a way similar to retrieve value from dropdownlist that can make the coding easier for radio buttons?

Link to comment
Share on other sites

JS

var radioButtons = document.form1.gender;var numberOfOptions = radioButtons.length;var i;var gender = "";for(i=0;i<numberOfOptions;i++){     if(radioButtons[i].checked)     {          gender = radioButtons[i].value;      }}

HTML

Male <input type="radio" name="gender" value="male"/><br/>Female <input type="radio name="gender" value="female"/>

Link to comment
Share on other sites

I tried this, but not working, plz help:

<script type="text/javascript">function getcheckvalue(){  var choices = document.form1.foodmenu  var numofchoices = choices.length  var food  var i  var j = 0  var k      for (i=0; i<numofchoices; i++)  {    if (choices[i].checked)	{   food[j].value = choices[i].value   j=j+1	}  }    for (k=0; k<food.length; k++)  {    //display the checked food   }</script>

<form name="form1" method="post" onsubmit="getcheckvalue()"><input type="checkbox" value="pizza" name="foodmenu" />pizza<input type="checkbox" value="spaghetti" name="foodmenu" />spaghetti<input type="checkbox" value="steak" name="foodmenu" />steak<input type="submit" value="submit" /></form>

Link to comment
Share on other sites

I see a couple of problems.Checkboxes cannot have the same name and do not group together so you cannot use choices.You did not declare var food as an array

var food = new Array()

and food would not have the propertie value anyways.you would check a checkbox like this

var checkbox = document.form1.checkbox1;var j;var food = new Array();if(checkbox.checked){    food[j] = checkbox.value;    j++;}

If you have a large number of checkboxes to check then you could make an array of the checkbox objects to loop through to save on code.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...