我可以将单选按钮设置为checked fine,但我想做的是设置一种“侦听器”,当某个单选按钮被选中时激活。
以以下代码为例:
$("#element").click(function()
{
$('#radio_button').attr("checked", "checked");
});
它添加了一个checked属性,一切都很好,但我该怎么做呢 添加警报。例如,选中单选按钮时弹出 没有点击功能的帮助?
我可以将单选按钮设置为checked fine,但我想做的是设置一种“侦听器”,当某个单选按钮被选中时激活。
以以下代码为例:
$("#element").click(function()
{
$('#radio_button').attr("checked", "checked");
});
它添加了一个checked属性,一切都很好,但我该怎么做呢 添加警报。例如,选中单选按钮时弹出 没有点击功能的帮助?
当前回答
这将工作在所有版本的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>
其他回答
如果你不想要点击功能 使用Jquery更改函数
$('#radio_button :checked').live('change',function(){
alert('Something is checked.');
});
这应该就是你想要的答案。 如果你使用的Jquery版本高于1.9.1 尝试使用on作为活动功能已被弃用。
$('#element').click(function() {
if($('#radio_button').is(':checked')) { alert("it's checked"); }
});
工作与所有类型的单选按钮和浏览器
if($('#radio_button_id')[0].checked) {
alert("radiobutton checked")
}
else{
alert("not checked");
}
工作Jsfiddle这里
你必须绑定复选框的单击事件,因为更改事件在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();
$('.radio-button-class-name').is('checked')不适合我,但下面的代码运行良好:
if(typeof $('.radio-button-class-name:checked').val() !== 'undefined'){
// radio button is checked
}