简体   繁体   English

组合复选框选择器以在jQuery中获得唯一结果

[英]Combining checkbox selectors for unique results in jQuery

I have 3 checkboxes, and I want all combinations of those checkboxes to display a different result, but I cannot work out how to do so. 我有3个复选框,我希望这些复选框的所有组合都显示不同的结果,但是我不知道该怎么做。 It feels like there's a simple way of doing this that I'm missing. 感觉好像有一种我缺少的简单方法。

Here's the Frankenstein monster-code I have so far, which doesn't do what I'd like it to. 这是我到目前为止拥有的科学怪人代码,但并没有达到我想要的效果。 The aim is that the following code sees that a user has has checked both the "webcam" (#checkWebcam) and "chat" (#checkChat) boxes, and that a different download link is being displayed based on that selection combo... 目的是使下面的代码看到用户已选中“网络摄像头”(#checkWebcam)和“聊天”(#checkChat)框,并且基于该选择组合显示了不同的下载链接。

jQuery('#checkWebcam, #checkChat').change(function() {
    var isChecked = jQuery('#checkWebcam, #checkChat').is(':checked');
    if(isChecked)
        jQuery('div.strip.download').html('<a href="<?php echo $nos; ?>" class="btn btn-lg btn-to gradient-to">Download</a>');
    else
        jQuery('div.strip.download').html('<a href="<?php echo $download; ?>" class="btn btn-lg btn-to gradient-to">Download</a>');
});

Could anyone help me with how to actually achieve this aim? 有人可以帮助我实现实际目标吗? Thank you in advance. 先感谢您。

This will do an OR operation, 这将执行OR运算,

var isChecked = jQuery('#checkWebcam, #checkChat').is(':checked');

what you basically need is to perform an AND opereation here, so use 您基本上需要在此处执行AND运算,因此请使用

var isChecked = jQuery('#checkWebcam').is(':checked') && $('#checkChat').is(':checked');

You can try this code : 您可以尝试以下代码:

if ( $("#checkWebcam:checked, #checkChat:checked").length == 2 ) {
    //your code
}

var isChecked = jQuery('#checkWebcam, #checkChat').is(':checked'); will return true if either one or both are selected. 如果选择一个或两个都将返回true

Modify your code as 修改您的代码为

jQuery('#checkWebcam, #checkChat').change(function() {
    var boxs = jQuery('#checkWebcam, #checkChat');
    var checked = boxs.filter(':checked'); //Filter checked checkboxes
    if(boxs.length == checked.length){ //if length are same
        alert('both are checked')
    }else{
        alert('both are not checked')
    }    
});

DEMO DEMO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM