获取两个Check-Boxs值



我有两个复选框,根据用户检查的内容,我必须运行3个不同的功能。

但是,我似乎无法正确获得值:

    $('#checks').click(function() {
        if (!$('#different-billing-address').is(":checked") && $('#ccheck').is(":checked")) {alert("function1");}
        if ($('#different-billing-address').is(":checked") && !$('#ccheck').is(":checked")) {alert("function2");}
        if (!$('#different-billing-address').is(":checked") && !$('#ccheck').is(":checked")) {alert("function3");}
    });
<input type="checkbox" id="different-billing-address" data-multiplier="0.9" name="deliveryAddressSameAsBillingAddress" aria-expanded="false">
<label for="different-billing-address" class="checkbox-button">Delivery address is the same as billing address </label>
<br>
<input type="checkbox" id="ccheck" style="float:left;">
<label id="ocpc" class="checkbox-button">&nbsp;Get it delivered to an Order and Collection Point</label>
<br>
<button id="checks">MyButton</button>

有人可以向我解释为什么这不起作用?

您的逻辑看起来不错。但是,没有足够的信息来说明为什么您的代码不起作用。它可能是由以下一个引起的:

  1. 请在您的代码的head部分或底部但在您的代码之前将jQuery包含在。
  2. 您需要将代码包装在 DOM准备就绪 $(function() { /* your code here */ });中,以确保DOM加载时触发代码。

以下演示使用您的逻辑并正常工作。

$(function() {
    var check1 = $('#different-billing-address'),
        check2 = $('#ccheck'),
        button = $('#checks');
    button.on('click', function() {
        if( !check1.is(':checked') && check2.is(':checked')  ) { console.log('Function1'); }
        if( check1.is(':checked') && !check2.is(':checked')  ) { console.log('Function2'); }
        if( !check1.is(':checked') && !check2.is(':checked') ) { console.log('Function3'); }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="different-billing-address" data-multiplier="0.9" name="deliveryAddressSameAsBillingAddress" aria-expanded="false">
<label for="different-billing-address" class="checkbox-button">Delivery address is the same as billing address </label>
<br>
<input type="checkbox" id="ccheck" style="float:left;">
<label id="ocpc" class="checkbox-button">&nbsp;Get it delivered to an Order and Collection Point</label>
<br>
<button id="checks">MyButton</button>

最新更新