Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ("checked", true) works, then doesn't work?

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?

like image 919
rybo111 Avatar asked Mar 16 '14 09:03

rybo111


2 Answers

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);
});
like image 160
Farhad Jabiyev Avatar answered Oct 14 '22 20:10

Farhad Jabiyev


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

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

Demo

Attributes vs. Properties

like image 38
Arun P Johny Avatar answered Oct 14 '22 18:10

Arun P Johny