You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

单选按钮切换时复选框状态无法正常变更的问题排查

Problem Root Cause

The issue happens because you’re using jQuery’s attr() method to control the checkbox’s checked state. For boolean attributes like checked, attr() only modifies the initial HTML attribute—not the dynamic DOM property that tracks the element’s current state. After the first user interaction, the browser updates the DOM’s checked property independently, so subsequent calls to attr() won’t reflect or change the checkbox’s visible state anymore.

Corrected jQuery Code

Replace attr() with prop() when setting the checkbox state. prop() directly interacts with the DOM’s live property, which is what controls the checkbox’s actual visible state:

$('input[name="inputMeal"]').on('change', function () {
    // Use 'this' to get the clicked radio's value directly (more efficient)
    const isSubMeal = $(this).val() === "0";
    $('input[name="chkIsPricing"]').prop('checked', isSubMeal);
});
Key Explanations
  1. Why prop() works: Unlike attr(), prop() updates the element’s live state property, which stays in sync with what the user sees and interacts with.
  2. Simplified logic: We removed the if/else block by directly evaluating whether the selected radio value is "0"—this returns a boolean (true/false) that we can pass straight to prop().
  3. Efficiency boost: Using $(this).val() avoids re-selecting the checked radio button every time, making the code cleaner and faster.
Quick Best Practice

In jQuery:

  • Use attr() for static HTML attributes (like id, class, value as defined in the initial markup).
  • Use prop() for dynamic state properties (like checked, disabled, selected), which change as users interact with the element.

内容的提问来源于stack exchange,提问作者weeraa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 08:57:38