user141164
user141164

Reputation: 51

Jquery CheckBox

var $field = $(this);
            if ($field.is('input')) {
                alert(1);
                if ($field.attr('type') == 'checkbox') {
                    alert(2);
                    if ($field.attr('value') == "true")
                        return $field.attr('checked');
                }

                return $field.val();
            }

I want to check if value of checkbox is true i add attribute checked = checked for checkbox. but my code is wrong. please help me.thanks

Upvotes: 2

Views: 12123

Answers (4)

JeffK
JeffK

Reputation: 128

CORRECTION:

.attr("checked") 

will return "checked" if checked (not true), "undefined" if not checked.

If you want a true/false then you have to do something like this:

$("#checker").attr("checked")=="checked"

Upvotes: 1

steampowered
steampowered

Reputation: 12062

.attr('checked') 

will return true for checked and undefined for unchecked

Upvotes: 1

Funka
Funka

Reputation: 4278

You can use the :checked selector to greatly help with this.

var $field = $(this);
return $field.is(':checked');

This will return a proper bool. If you return the attr('checked') or the val(), you'll end up with a string, which is probably not what you want.

See http://docs.jquery.com/Selectors/checked

Upvotes: 16

rahul
rahul

Reputation: 187010

Change the condition to

$("input:checkbox").val() == "true"

and for checking the checkbox you can use

$("input:checkbox").attr ( "checked" , true );

You can select a checkbox using

$("input:checkbox")

and value using

$("input:checkbox").val()

If you want to check all the checkboxes with attribute value true then you can use

$(document).ready ( function ()
        {
            var checkBoxes = $("input:checkbox");           
            checkBoxes.each ( function () {
                if ( $(this).val() == "true" )
                {
                    $(this).attr ( "checked" , true );
                }
            });
        });

Upvotes: 6

Related Questions