不使用onclick实现jQuery单选框选中时触发alert的解决方案
修复方案
原代码错误说明
- 选择器不匹配:jQuery 调用时选中的 ID 为
#vendor-date-method-checkbox,但实际单选框的 ID 是vendor-date-method-checkbox2,后缀缺失导致无法匹配到目标元素 - 所有单选框都加了
disabled属性,处于不可交互状态,无法被选中 - 仅定义了
test函数但没有绑定触发规则,函数不会自动执行,不需要写onclick属性的话可以通过 JS 绑定单选组的change事件监听选择状态变化
完整可运行代码
JS 部分
jQuery(function($) { // 监听单选组的选择变化事件,无需在HTML中写onclick $('input[name="vendor-method-checkbox2"]').on('change', function() { if ($("#vendor-date-method-checkbox2").prop("checked")) { alert('yes'); } else { alert('no'); } }); // 如果需要页面加载完成就主动判断一次状态,放开下面一行的注释 // $('input[name="vendor-method-checkbox2"]').trigger('change'); });
HTML 部分(移除了无用的disabled属性)
<input type="radio" id="vendor-date-method-checkbox2" name="vendor-method-checkbox2" value="vendor-date-method-checkbox" autocomplete="off"> <label for="vendor-date-method-checkbox2">Date Method</label> <br> <input type="radio" id="vendor-custom-method-checkbox2" name="vendor-method-checkbox2" value="vendor-custom-method-checkbox" autocomplete="off"> <label for="vendor-custom-method-checkbox2">Custom Input Method</label> <br> <input type="date" id="deposit-due2" name="deposit-due" maxlength="2" size="4" class="deposit-input" autocomplete="off" placeholder="ie 'upon '">
如果你的判断逻辑不需要在单选切换时触发,而是在其他操作(比如点击提交按钮)时才执行,直接把上述if判断逻辑放到对应操作的触发函数中即可,只需保证选择器和实际元素ID一致。
内容的提问来源于stack exchange,提问作者Manny
相关产品推荐
相关产品推荐

