简体   繁体   中英

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 first. This will input "New preset value" and check the second checkbox.
  2. Click to clear the whole form. 以清除整个表单。
  3. Click again. This will input "New preset value" check the second checkbox. 检查第二个复选框。

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

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);
});

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

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

Demo

Attributes vs. Properties

使用prop()而不是attr()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM