我试图这样做,以便如果我们页面上的复选框被选中,它将显示一条警告消息,通知用户他们已选择显示他们的结帐历史记录.如果用户取消选中该复选框,则应显示另一个警告框,让他们知道他们选择不显示其结帐历史记录.如果选中/取消选中复选框,则无法显示警告框.这是我的代码.
<div class="myAccountCheckBoxHolder" id="showCheckoutHistoryCheckBox"> <input tabindex="40" checked="checked" id="showCheckoutHistory" name="showCheckoutHistory" type="checkBox"> <label for="showCheckoutHistory" class="checkLabel">Show my checkout history</label> </div>
使用Javascript
function validate() { var checkoutHistory = document.getElementById('showCheckoutHistory'); if (checkoutHistory.checked) { alert("You have elected to show your checkout history."); } else { alert("You have elected to turn off checkout history."); }
谢谢.
解决方法
jQuery(原始答案)
jQuery(document).ready(function() { jQuery('#showCheckoutHistory').change(function() { if ($(this).prop('checked')) { alert("You have elected to show your checkout history."); //checked } else { alert("You have elected to turn off checkout history."); //not checked } }); });
文档:http://api.jquery.com/prop/
JavaScript(2018更新)
值得注意的是,您不需要任何javascript库来实现它.
// Check current state and save it to "checked" variable var checked = document.getElementById("showCheckoutHistory").checked; // Set state manually (change actual state) document.getElementById("showCheckoutHistory").checked = true; // or document.getElementById("showCheckoutHistory").checked = false;
对于更纯粹的JavaScript解决方案,我推荐vanilla.js:http://vanilla-js.com/框架;)