jQuery - is a radio button or a check-box checked?
I开发者_Go百科 have a UI that can either use a checkbox or a pair of radio buttons with values of 0 and 1 to allow the user to insert a boolean.
I have an event handler being called when the checkbox or either of the radio buttons is clicked on.
If the checkbox is checked, or if the radio button with a value of 1 is selected, I want to do one thing, if the checkbox is not checked, or the radio button with a value of 0 is selected, or if neither radio button is selected, I want to do another.
Here's the complication - I need to have the same event handler called, regardless of whether it is attached to a check box or a radio button.
So the question is, what is the cleanest way of structuring the code? Element.is('checked') doesn't work, because it returns true if either radio button is selected. Element.val() doesn't work, because the checkbox always has constant value.
Ideas?
use onChange to trigger the event. Then, you can check the TYPE attribute and split the logic there (if checkbox, check if it's checked, if radio, then check the value):
$('.myInput').change(function(){
if($(this).attribute('type')=='radio'){
... get the value ...
} else {
... see if it's checked ...
}
})
精彩评论