get value of checkbox

I am trying to obtain the value of the checkbox (whether it is checked or not) using this code:

  $('input[type="checkbox"]').each(function ()
            {
                var str = $(this).attr("ID");
                var last = str.split("_").pop();
                customstring[last] = $(this).val();
            });


$(this).val();

is returning "on"  whether the box is checked or not!  Obviously that won't do.  :)


How do I do it the correct way?
LVL 5
Tom KnowltonWeb developerAsked:
Who is Participating?
 
leakim971PluritechnicianCommented:
lol

to get the value (checked or not checked use :  $(this).is(":checked"); // return true or false

else you're trying to get the value, look like your checkboxes don't have value, the default one is "on"
0
 
leakim971PluritechnicianCommented:
http://jsfiddle.net/tD5Ln/

versus

http://jsfiddle.net/k6zCs/

<input type="checkbox" id="c_chk0" value="0" />
<input type="checkbox" id="c_chk1" value="1" />
<input type="checkbox" id="c_chk2" value="2" />
<input type="checkbox" id="c_chk3" value="3" />
<input type="checkbox" id="c_chk4" value="4" />

Open in new window

var customstring = {};
$('input[type="checkbox"]').each(function (){
    var str = $(this).attr("ID");
    var last = str.split("_").pop();
    customstring[last] = $(this).val();
});
alert(JSON.stringify(customstring));

Open in new window


VERSUS

<input type="checkbox" id="c_chk0" />
<input type="checkbox" id="c_chk1" checked="checked" />
<input type="checkbox" id="c_chk2" />
<input type="checkbox" id="c_chk3" />
<input type="checkbox" id="c_chk4" />

Open in new window

0
 
leakim971PluritechnicianCommented:
check this one : http://jsfiddle.net/k6zCs/2/

var customstring = {};
$('input[type="checkbox"]').each(function (){
    var str = $(this).attr("ID");
    var last = str.split("_").pop();
    customstring[last] = $(this).is(":checked")?"on":"off";
});
alert(JSON.stringify(customstring));
0
 
Tom KnowltonWeb developerAuthor Commented:
???
0
 
Tom KnowltonWeb developerAuthor Commented:
thx!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.