Find out if radio button is checked with JQuery?
I can set a radio button to checked fine, but what I want to do is setup a sort of 'listener' that activates when a certain radio button is checked.
Take, for example the following code:
$("#element").click(function()
{
$('#radio_button').attr("checked", "checked");
});
it adds a checked attribute and all is well, but how would I go about adding an alert. For example, that pops up when the radio button is checked without the help of the click function?
$('#element').click(function() {
if($('#radio_button').is(':checked')) { alert("it's checked"); }
});
If you have a group of radio buttons sharing the same name attribute and upon submit or some event you want to check if one of these radio buttons was checked, you can do this simply by the following code :
$(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!');
}
});
});
Source
jQuery API Ref
As Parag's solution threw an error for me, here's my solution (combining David Hedlund's and Parag's):
if (!$("input[name='name']").is(':checked')) {
alert('Nothing is checked!');
}
else {
alert('One of the radio buttons is checked!');
}
This worked fine for me!
链接地址: http://www.djcxy.com/p/14616.html上一篇: jquery停止孩子触发父事件
下一篇: 找出是否用JQuery检查单选按钮?