我有一个带有三个复选框的小型 html 表单
,每个 行
一个。我想在用户取消选中该框时显示一个 javascript 确认框
,然后如果用户选择取消,则 checkbox
保持选中状态。我搜索了这个网站和其他几个网站,但几乎所有内容都与选中的 checkbox
有关,比如他们是否必须同意某些条款或其他内容。我是 Javascript
的新手,但是我尝试根据我认为它应该看起来的样子创建一个函数,但它不起作用。
这是我的表格:
<form action="" method="post">
<table id="table">
<tr>
<td>Checkbox One</td>
<td align="center">
<input type="checkbox" name="check1" checked="checked" onchange="cTrig(this.name)"></input>
</td>
</tr>
<tr>
<td>Checkbox Two</td>
<td align="center">
<input type="checkbox" name="check2" checked="checked" onchange="cTrig(this.name)"></input>
</td>
</tr>
<tr>
<td>Checkbox Three</td>
<td align="center">
<input type="checkbox" name="check3" checked="checked" onchange="cTrig(this.name)"></input>
</td>
</tr>
<tr align="center">
<td colspan="2">
<input type="submit" name="submit" value="submit"></input>
</td>
</tr>
</table>
</form>
这是我试过但不起作用的功能:
function cTrig(name) {
if (name.checked == true) {
confirm("Are you sure you want to do this?");
return true;
} else {
return false;
}
}
这是一个jsfiddle
我更喜欢 Javascript
中的一些东西,因为我想在进入 jquery
之前更加熟悉该语言,但是如果它必须在 jquery 中完成
,那就没问题了。干杯。
最佳答案
试试这个方法
<form action="" method="post">
<table id="table">
<tr>
<td>Checkbox One</td>
<td align="center">
<input type="checkbox" name ="check1" id="check1" checked='checked' onchange="cTrig('check1')"></input>
</td>
</tr>
<tr>
<td>Checkbox Two</td>
<td align="center">
<input type="checkbox" name="check2" id="check2" checked='checked' onchange="cTrig('check2')"></input>
</td>
</tr>
<tr>
<td>Checkbox Three</td>
<td align="center">
<input type="checkbox" id="check3" name="check3" checked='checked' onchange="cTrig('check3')"></input>
</td>
</tr>
<tr align="center">
<td colspan="2">
<input type="submit" name="submit" value="submit"></input>
</td>
</tr>
</table>
</form>
使用元素 ID
function cTrig(clickedid) {
if (document.getElementById(clickedid).checked == true) {
return false;
} else {
var box= confirm("Are you sure you want to do this?");
if (box==true)
return true;
else
document.getElementById(clickedid).checked = true;
}
}
使用名称
function cTrig(clickedid) {
if (document.getElementsByName(clickedid)[0].checked == true) {
return false;
} else {
var box= confirm("Are you sure you want to do this?");
if (box==true)
return true;
else
document.getElementsByName(clickedid)[0].checked = true;
}
}
关于javascript - 如何在未选中复选框时显示 Javascript 确认框,然后如果用户选择取消,则选中该复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14208022/