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

不使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 01:45:04