简体   繁体   English

jQuery(如果已选中单选按钮)

[英]jQuery if radio button is selected

I have this bit of code here: 我在这里有这段代码:

$(document).ready(function(){
    $("input[name=MMERGE8]:radio").click(function () {
        var checked = $(this).attr('checked');
        alert(checked);
    });
});

I am trying to check if a radio button is checked or not and store that into a variable. 我正在尝试检查是否选中了单选按钮,并将其存储到变量中。 But when i run this code checked returns as undefined. 但是,当我运行此代码时,检查返回的结果为未定义。 Why? 为什么?

From the click event you can just use this.value to find out which value is selected in the group as the click event is always going to set the radio as checked for the radio group. 从click事件中,您可以仅使用this.value来找出在组中选择了哪个值,因为click事件将始终将单选按钮设置为选中的单选按钮。

$('[name="test"]').click(function () {
    alert(this.value)
});

if you were trying to get the value from another event you would use a selector for the group and get the checked item. 如果您试图从另一个事件获取值,则可以使用该组的选择器并获取选中的项。

$('#getValue').click(function () {
    alert($('[name="test"]:checked').val());
});

Examples here... http://jsfiddle.net/SeanWessell/7hb71jga/ 此处的示例... http://jsfiddle.net/SeanWessell/7hb71jga/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM