In Action

Using JQuery to get Checkbox Input

Checkboxes are similar to radio buttons with one big exception. With a Checkbox fieldset more than one checkbox can be selected.

 

Which of the following languages allow for object oriented code

A.   Java
B.   C++
C.   Perl
D.   Php
E.   Javascript




JQuery Code

JQuery Code for our example

In this example we are accessing getting the value of the checked property. However, unlike the radio button example since we can have more than one selection we must use the .each(function().

   $("#checkanswer").click( function() {   
         var cbvals = "";
         $("#form1 input:checked").each(function() {   
             //alert( $(this).attr('id') ); 
             cbvals += $(this).attr('id'); 
             $("#feedback").text(cbvals);
   });  
         }); 

HTML Code

HTML Code for our example

<fieldset>
    <p id="stem">Which of the following languages allow for object oriented code</p>
<p>
	A. <input type="checkbox" name="Java" value="Java" id="a" />  Java<br /> 
  B. <input type="checkbox" name="C++" value="C++" id="b" />  C++<br />   
  C. <input type="checkbox" name="Perl" value="Perl" id="c" />  Perl<br /> 
  D. <input type="checkbox" name="Php" value="Php" id="d" />  Php<br /> 
  E. <input type="checkbox" name="Javascript" value="Javascript" id="e" />  Javascript
</p>	
    <p>
      <input name="hiddenField" type="hidden" value="C" id="ans" />
      <br />
  </p>
    </fieldset>
  </form>
  <p>
 <button id="checkanswer">Who is checked?</button>
  </p>