单选按钮切换时复选框状态无法正常变更的问题排查
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
- Why
prop()works: Unlikeattr(),prop()updates the element’s live state property, which stays in sync with what the user sees and interacts with. - 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 toprop(). - 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 (likeid,class,valueas defined in the initial markup). - Use
prop()for dynamic state properties (likechecked,disabled,selected), which change as users interact with the element.
内容的提问来源于stack exchange,提问作者weeraa
相关产品推荐
相关产品推荐

