tags:

views:

23

answers:

1

In the script below, how do I get the values of only radio buttons and checkboxes that have been selected and not all (provided a radio button and checkbox were selected).

Right now it gives me the values of all, whether selected or not, and also the submit button (which i dont need).

How do i do this? There'll be more checkboxes and radio buttons, i've used only 2 sets for this question.

<html> 
<head> 
<script type="text/javascript"> 
function DisplayFormValues() 
{ 
var str = ''; 
var elem = document.getElementById('frmMain').elements; 

for(var i = 0; i < elem.length; i++) 
{
str += elem[i].value+"<br>";
} 

document.getElementById('lblValues').innerHTML = str; 
} 

</script> 
</head> 
<body> 

<form id="frmMain" name="frmMain"> 
<INPUT TYPE="radio" NAME="r1" value="r1a">
<INPUT TYPE="radio" NAME="r1" value="r1b">
<INPUT TYPE="radio" NAME="r1" value="r1c">

<INPUT TYPE="checkbox" NAME="c1" value="c1a">
<INPUT TYPE="checkbox" NAME="c1" value="c1b">
<INPUT TYPE="checkbox" NAME="c1" value="c1c">

<input type="button" value="Test" onclick="DisplayFormValues();" /> 
</form> 
<hr /> 
<div id="lblValues"></div> 
</body> 
</html>
+1  A: 

Add the following test:

if(elem[i].checked)
  str += elem[i].value+"<br>";

Also, if you use jQuery, the whole script is even simpler:

function DisplayFormValues(){
  $("input:checkbox:checked").add("input:radio:checked")
    .each(function(){
      $("div#lblValues").append(this.value + "<br>");
  });
}
Hollister