views:

1043

answers:

4
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  A: 

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 );
          }
      });
     });
rahul
+4  A: 

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

Funka
A: 

I'm try use Phoenix way but it's still wrong.
Code Line:

if ( $(this).val() == "true" )
  {
     $(this).attr ( "checked" , true );
  }

can't run. I used to alert() to check wrong but it not run.

Please help me
best regards,
Vicky

both lines here seem wrong. Remember that a checkbox will always have the same "val" regardless of being checked or not. (For example, view source, and see where it says <input value="whatever" />. Furthermore your second line of code seems like you want to check the already checked checkbox? (In which case, you'd want to say attr('checked', 'checked') to do this...) It might help if you updated your original post and tell us what you're trying to accomplish...
Funka
A: 

.attr("checked") will return true for checked and false for unchecked

user523421