javascript - 选中/取消选中单选按钮

标签 javascript jquery html

$("input[type='radio']").each(function() {
  if ($(this).is(":checked")) {
    $(this).css('background', 'blue');
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" data="cool" name="cool" checked="checked">
<input type="radio" data="cool" name="cool">
<input type="radio" data="cool" name="cool">

我的方法是首先检查我的输入是否为 :checked,如果是,则放置一些具有背景颜色的 CSS 类。我做到了这一点,接下来我要做的是在用户单击单选按钮或任何其他(更好的)想法时删除 :checked 。提交表单后,此代码检查输入是否为 :checked,问题是当我想选择另一个单选按钮时,我得到如下内容:

a busy cat

1和2单选按钮被选中,应该只有2个:checked

最佳答案

您需要添加 else 来移除蓝色,例如:

$("input[type='radio']").each(function () {
   if ($(this).is(":checked")) {
      $(this).css('background', 'blue');
   }else{
     $(this).css('background', 'white');
   }
});

您还可以为这些 radio 附加点击事件,例如:

$("body").on("click", "input[type='radio']", function () {
    $("input[type='radio']").css('background', 'white');
    $(this).css('background', 'blue');
});

关于javascript - 选中/取消选中单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56340451/

相关文章:

javascript - Knockout js隐藏图片div

javascript - 查找字符串中出现时间最长的 "aeiou"

javascript - !!(new Number(0)) == true,但是 !!(Number(0)) == false,为什么?

javascript - 移除/恢复元素,维护它们的事件和元素的子元素

html - 在其 <li> 子元素中也观察到悬停在 <ul> 上的反弹效果

javascript - 根据输入过滤列表

javascript - 如何在提交表单之前获取JSON中的表单所有元素值

javascript - 使用 html 和 css 创建树

html - 主元素不得作为节元素的后代出现

javascript - 遍历数组并检查 jQuery 中 <td> 单元格的值