r.d*_*ano 6 javascript checkbox jquery alert
我试图这样做,以便如果我们页面上的复选框被选中,它将显示一条警告消息,通知用户他们已选择显示他们的结帐历史记录.如果用户取消选中该复选框,则应显示另一个警告框,让他们知道他们选择不显示其结帐历史记录.如果选中/取消选中复选框,则无法显示警告框.这是我的代码.
HTML
<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>
Run Code Online (Sandbox Code Playgroud)
使用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.");
}
Run Code Online (Sandbox Code Playgroud)
谢谢.
Jac*_*ski 20
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
}
});
});
Run Code Online (Sandbox Code Playgroud)
文档: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;
Run Code Online (Sandbox Code Playgroud)
对于更纯粹的JavaScript解决方案,我推荐vanilla.js:http://vanilla-js.com/ framework;)
因此,对于复选框更改,我使用changejQuery提供的侦听器.所以让你的javascript:
$("#showCheckoutHistory").change(function(event){
if (this.checked){
alert("You have elected to show your checkout history.");
} else {
alert("You have elected to turn off checkout history.");
}
});
Run Code Online (Sandbox Code Playgroud)
在这里它是一个工作小提琴.
这是一个没有jQuery的工作版本.实际上,一旦函数有一个右括号,你的代码就能很好地工作.我刚刚为你添加了一个事件监听器,并将checkoutHistoryvar 移到了函数之外.
var checkoutHistory = document.getElementById('showCheckoutHistory');
checkoutHistory.onchange = function() {
console.log(checkoutHistory);
if (checkoutHistory.checked) {
alert("You have elected to show your checkout history.");
} else {
alert("You have elected to turn off checkout history.");
}
}
Run Code Online (Sandbox Code Playgroud)
这是我用过的JSFiddle.http://jsfiddle.net/aaFe5/
| 归档时间: |
|
| 查看次数: |
47256 次 |
| 最近记录: |