Dmitry F
Dmitry F

Reputation: 1670

jQuery: uncheck/check checkboxes when those have checked attribute on page load

http://jsfiddle.net/dmitryfil/4pYaW/1/

HTML:

<input type="checkbox" name="item-a" checked="checked" />
<input type="checkbox" name="item-b" />
<input type="checkbox" name="item-c" />

<hr />

<select multiple>
    <option value="a">a</option>
    <option value="b">b</option>
</select>

JS:

$('input[type=checkbox]:checked').attr('checked', false);
//$('input[type=checkbox]:checked).removeAttr('checked');

$('select option').each(function(i, el){
    var val = $(this).attr('value');
    $('input[name=item-'+val+']').attr('checked', 'checked');
    //$('input[name=item-'+val+']').attr('checked', true);
});

Notes:

Thanks a lot for any suggestions.

Upvotes: 0

Views: 2770

Answers (2)

Jashwant
Jashwant

Reputation: 29005

Try this,

$('select option').each(function(i, el){
    var val = $(this).prop('value');
    $('input[name=item-'+val+']').prop('checked', 'checked');
    //$('input[name=item-'+val+']').attr('checked', true);
});

Demo

A prop() is not same as attr() . prop() changes the property of an element where as attr() changes the attribute (the one written in html element )

I would highly advice you to go through all the answers here at .prop() vs .attr()

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Use .prop to change runtime properties of dom elements like checked and selected.

The value for these properties are boolean values like true/false instead of checked/selected.

$('input[name=item-'+val+']').prop('checked', true);

Demo: Fiddle

Upvotes: 2

Related Questions