简体   繁体   English

获取两个复选框值

[英]Get two check-boxes value

I have two checkboxes which I have to run 3 different functions depending on what's checked by the user.我有两个复选框,我必须根据用户检查的内容运行 3 个不同的功能。

However I don't seem to be able to get the values correctly:但是我似乎无法正确获取值:

 $('#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>

Can someone explain to me why is this not working?有人可以向我解释为什么这不起作用吗?

Your logic looks fine.你的逻辑看起来不错。 However, there's not enough information to tell why your code does not work.但是,没有足够的信息来说明为什么您的代码不起作用。 It could have been caused by one of the following:它可能是由以下原因之一引起的:

  1. Please include jQuery in the head section of your code or at the bottom but right before your code.请在代码的head或底部但在代码之前包含 jQuery。
  2. You need to enclose your code in DOM ready $(function() { /* your code here */ });你需要将你的代码包含在DOM 中$(function() { /* your code here */ }); to ensure your code fires when the DOM has loaded.以确保您的代码在DOM加载时触发。

The following demo uses your logic and works fine.以下演示使用您的逻辑并且工作正常。

 $(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>

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

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