选择两个不同的单选按钮后如何触发事件 [英] How to fire an event after two different radio buttons are selected

查看:150
本文介绍了选择两个不同的单选按钮后如何触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两组单选按钮:

<input type="radio" name="amount" value="1"/>
<input type="radio" name="amount" value="2"/>

<input type="radio" name="book" value="fiction"/>
<input type="radio" name="book" value="novel"/>

 function myEvent(){
    //do something
}
 

我想触发一个事件,特别是在选中两个单选按钮时触发另一个函数的调用.我试过使用click()change()函数,但是,在选中第一个单选按钮之后会调用该函数.我只想在两个单选按钮都选中后才能调用函数.我该怎么做?

解决方案

类似的方法应该起作用:

$(':radio').change(function() {
    if($(':radio:checked').length === 2) {
        myEvent();
    }
});

关键部分是if语句,该语句选择所有checked单选按钮,然后确保在调用函数之前,确实有两个按钮(使用所得jQuery对象的length属性). /p>

I have two groups of radio buttons:

<input type="radio" name="amount" value="1"/>
<input type="radio" name="amount" value="2"/>

<input type="radio" name="book" value="fiction"/>
<input type="radio" name="book" value="novel"/>

function myEvent(){
    //do something
}

I want to fire an event, specifically a call to another function when both radio buttons are checked. I've tried using the click(), and change() functions, however, the call to the function occurs after the first radio button is checked. I want to call a function only after both radio buttons are checked. How do I do this?

解决方案

Something like this should work:

$(':radio').change(function() {
    if($(':radio:checked').length === 2) {
        myEvent();
    }
});

The key part is the if statement, which selects all checked radio buttons, then makes sure there's exactly two of them (using the length property of the resulting jQuery object), before calling the function.

这篇关于选择两个不同的单选按钮后如何触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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