且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

选择两个不同的单选按钮后如何触发事件

更新时间:2023-10-30 15:01:52

类似的方法应该起作用:

$(':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.