我可以将单选按钮设置为checked fine,但我想做的是设置一种“侦听器”,当某个单选按钮被选中时激活。
以以下代码为例:
$("#element").click(function()
{
$('#radio_button').attr("checked", "checked");
});
它添加了一个checked属性,一切都很好,但我该怎么做呢 添加警报。例如,选中单选按钮时弹出 没有点击功能的帮助?
我可以将单选按钮设置为checked fine,但我想做的是设置一种“侦听器”,当某个单选按钮被选中时激活。
以以下代码为例:
$("#element").click(function()
{
$('#radio_button').attr("checked", "checked");
});
它添加了一个checked属性,一切都很好,但我该怎么做呢 添加警报。例如,选中单选按钮时弹出 没有点击功能的帮助?
当前回答
如果你有一组单选按钮共享相同的name属性,并且在提交或某些事件时,你想检查这些单选按钮中的一个是否被选中,你可以简单地通过以下代码做到这一点:
$(document).ready(function(){
$('#submit_button').click(function() {
if (!$("input[name='name']:checked").val()) {
alert('Nothing is checked!');
return false;
}
else {
alert('One of the radio buttons is checked!');
}
});
});
源
jQuery API参考
其他回答
试试这个
if($('input[name="radiobutton"]:checked').length == 0) {
alert("Radio buttons are not checked");
}
$('#element').click(function() {
if($('#radio_button').is(':checked')) { alert("it's checked"); }
});
你必须绑定复选框的单击事件,因为更改事件在IE中不起作用。
$('#radio_button').click(function(){
// if ($(this).is(':checked')) alert('is checked');
alert('check-checky-check was changed');
});
现在,当你以编程方式改变状态时,你也必须触发这个事件:
$('#radio_button').attr("checked", "checked");
$('#radio_button').click();
如果你不想要点击功能 使用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>