jQuery-是否选中了单选按钮或复选框? [英] jQuery - is a radio button or a check-box checked?

查看:120
本文介绍了jQuery-是否选中了单选按钮或复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UI,可以使用复选框或一对值为0和1的单选按钮来允许用户插入布尔值.

I 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.

如果选中此复选框,或者如果选择了值为1的单选按钮,那么我想做一件事,如果未选中此复选框,或者选择了值为0的单选按钮,或者两个单选按钮都没有选中,我想再做一个.

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.

问题是,构造代码的最干净的方法是什么? Element.is('checked')不起作用,因为如果选择了任何一个单选按钮,它将返回true. Element.val()不起作用,因为该复选框始终具有恒定值.

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.

想法?

推荐答案

使用onChange触发事件.然后,您可以检查TYPE属性并在其中拆分逻辑(如果是复选框,请检查是否已选中,如果是单选,则请检查值):

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 ...
    }
})

这篇关于jQuery-是否选中了单选按钮或复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆