Jquery 单选框选中查找显示以前选中的项目

Jquery Radio box checked find is showing previously checked Item

本文关键字:项目 查找 单选框 Jquery 显示      更新时间:2023-09-26

我有这个html

<div   class="calsort btn-group" data-toggle="buttons">
    <label class="btn btn-primary ">
        <input type="radio" name="options" id="rcal1" autocomplete="off" checked="checked">rcal1</label>
    <label class="btn btn-primary">
        <input type="radio" name="options" id="rcal2" autocomplete="off">rcal2</label>
    <label class="btn btn-primary">
        <input type="radio" name="options"  id="rcal3" autocomplete="off">rcal3</label>
</div>

还有我的JavaScript

$( ".calsort" ).click(function() {
$(".calsort :checked").each(function() {
rcal = this.id;
    alert(rcal);
});
});

因此,当我在 js 小提琴中测试此功能时,它可以工作......但是当我使用其他 js 代码在工作环境中进行测试时,这是不起作用的......但是这个函数单独不涉及任何其他变量名或函数名。

我的问题是当我单击 rcal2

按钮时,它会首先提醒 rcal1,当我第二次单击时它会提醒 rcal2。rcal3按钮也是如此。第一次它提醒以前检查的值。

有人可以告诉其他方法来检查选中哪个框...我不想要$(这个)方法。因为其他函数也将使用这种循环方式。

当您单击lable而不是radio button时,就会发生这种情况。原因是当您单击标签时发生单击事件时,先前选中的按钮未清除。它甚至发生在 jsfiddle 中(尝试单击此处的标签)。

试试这个,

$( ".calsort input" ).click(function() {
    var rcal = this.id;
    alert(rcal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div   class="calsort btn-group" data-toggle="buttons">
    <label class="btn btn-primary ">
        <input type="radio" name="options" id="rcal1" autocomplete="off" checked="checked">rcal1</label>
    <label class="btn btn-primary">
        <input type="radio" name="options" id="rcal2" autocomplete="off">rcal2</label>
    <label class="btn btn-primary">
        <input type="radio" name="options"  id="rcal3" autocomplete="off">rcal3</label>
</div>

这是另一种方法,而不是.click()事件使用了.change()。事件.change()单选按钮是获取所选值的好方法。

.JS:

工作演示

$(".calsort input").on('change', function () {
    var self = jQuery(this);
    var aResult = self.is(":checked");
    if (aResult) {
        alert(self.attr('id'));
    }
});