我可以将单选按钮设置为checked fine,但我想做的是设置一种“侦听器”,当某个单选按钮被选中时激活。

以以下代码为例:

$("#element").click(function()
{ 
    $('#radio_button').attr("checked", "checked");
});

它添加了一个checked属性,一切都很好,但我该怎么做呢 添加警报。例如,选中单选按钮时弹出 没有点击功能的帮助?


当前回答

解决方案很简单,因为当某个单选按钮被选中时,你只需要“监听器”。这样做:

if($('#yourRadioButtonId').is(':checked')){ 
// Do your listener's stuff here. 
}

其他回答

试试这个

    if($('input[name="radiobutton"]:checked').length == 0) {
        alert("Radio buttons are not checked");
    }

工作与所有类型的单选按钮和浏览器

if($('#radio_button_id')[0].checked) {
   alert("radiobutton checked")
}
else{
   alert("not checked");
}

工作Jsfiddle这里

试试这个:

alert($('#radiobutton')[0].checked)

如果你不想要点击功能 使用Jquery更改函数

$('#radio_button :checked').live('change',function(){
alert('Something is checked.');
});

这应该就是你想要的答案。 如果你使用的Jquery版本高于1.9.1 尝试使用on作为活动功能已被弃用。

这将工作在所有版本的jquery。

//-- Check if there's no checked radio button
if ($('#radio_button').is(':checked') === false ) {
  //-- if none, Do something here    
}

当某个单选按钮被选中时,激活某个功能。

// get it from your form or parent id
    if ($('#your_form').find('[name="radio_name"]').is(':checked') === false ) {
      $('#your_form').find('[name="radio_name"]').filter('[value=' + checked_value + ']').prop('checked', true);
    }

html

$('document').ready(function() { var checked_value = 'checked'; if($("#your_form").find('[name="radio_name"]').is(":checked") === false) { $("#your_form") .find('[name="radio_name"]') .filter("[value=" + checked_value + "]") .prop("checked", true); } } ) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form action="" id="your_form"> <input id="user" name="radio_name" type="radio" value="checked"> <label for="user">user</label> <input id="admin" name="radio_name" type="radio" value="not_this_one"> <label for="admin">Admin</label> </form>