0

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

  • Browser - Chrome
  • I have a series of checkboxes where one is checked by default.
  • I have a select with a 2 options (where value of an option is linked to checkbox)
  • When I try to check checkboxes, based on a select (so 2 should be selected), only 1 checkbox gets selected, and that's what I'm trying to figure out, why?

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:

  • if checkbox is not checked by default, it works fine.
  • when I unchecking with: attr('checked', false) and removeAttr('checked') - those produce different results.

Thanks a lot for any suggestions.

Dmitry F
  • 1,650
  • 1
  • 15
  • 20

2 Answers2

2

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

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()

Community
  • 1
  • 1
Jashwant
  • 28,410
  • 16
  • 70
  • 105