6

Please see this Fiddle

HTML:

<form>
  <button type="button" class="form-clear">Clear</button>
  <button type="button" class="form-set">Set</button>
  <input type="text" value="Preset value" />
  <input type="checkbox" checked/>
  <input type="checkbox" />
</form>

jQuery:

$(".form-clear").click(function(){
  $(':input').not(':button, :submit, :reset, :hidden').val('');
  $(':checkbox, :radio').attr('checked', false);
});
$(".form-set").click(function(){
  $(':input').not(':button, :submit, :reset, :hidden').val('New preset value');
  $(':checkbox, :radio').attr('checked', true);
});
  1. Click Set first. This will input "New preset value" and check the second checkbox.
  2. Click Clear to clear the whole form.
  3. Click Set again. This will input "New preset value" but will not check the second checkbox.

I'm guessing there's a conflict between the two functions?

rybo111
  • 12,240
  • 4
  • 61
  • 70

3 Answers3

18

The most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox.

Use .prop() instead of the .attr().

$(".form-clear").click(function(){
    $(':input').not(':button, :submit, :reset, :hidden').val('');
    $(':checkbox, :radio').prop('checked', false);
});
$(".form-set").click(function(){
    $(':input').not(':button, :submit, :reset, :hidden').val('New preset value');
    $(':checkbox, :radio').prop('checked', true);
});
Farhad Jabiyev
  • 26,014
  • 8
  • 72
  • 98
6

You need to use .prop() to set the checked property

$(':checkbox, :radio').prop('checked', true);

Demo

Attributes vs. Properties

martynas
  • 12,120
  • 3
  • 55
  • 60
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

Use prop() instead of attr()

$(':checkbox, :radio').prop('checked', true);

tchow002
  • 1,068
  • 6
  • 8