2
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

1
  • Can you give more context? It is not clear where "this" is. Commented Aug 28, 2009 at 4:24

4 Answers 4

16

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

Sign up to request clarification or add additional context in comments.

Comments

6

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 );
                }
            });
        });

Comments

1
.attr('checked') 

will return true for checked and undefined for unchecked

Comments

1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.