我想要一条消息“你确定吗?”在用户尝试取消选中复选框时显示。如果他们选择“是”之类的东西,那么取消选中它。如果他们选择“否”,则保持原样。我对JavaScript很新,我对此的尝试促使我出现错误“JavaScript运行时错误:无法获取未定义或空引用的属性'”。这是我的Checkbox代码:
<div id="ChkBox">
<input style="margin: 5px; " type="checkbox" name="chkIsActive" onchange="Areyousure('ChkBox')" value="@Model.Pharmacy.IsActive" @(Model.Pharmacy.IsActive =="True" ? "checked=\"checked\"" : "") /> Is Active
</div>
<script>
Areyousure();
</script>
这是函数:
function Areyousure(id) {
if (document.getElementById(id).checked == true) {
return false;
} else {
var box = confirm("Are you sure you want to Uncheck this?");
if (box == true)
return true;
else
document.getElementById(id).checked = true;
}
}
我该怎么做才能解决这个问题?在此先感谢!
答案 0 :(得分:2)
您可以考虑传入元素本身以避免因使用以下id
属性定位它而导致的任何问题:
onchange='Areyousure(this);'
然后相应调整您的函数以确定checked
属性是否应该通过更改持续存在:
function Areyousure(element) {
// If it is checked now, let it be
if (element.checked) {
return false;
// Otherwise prompt the user
} else {
// Prompt the user to make sure
if (confirm("Are you sure you want to Uncheck this?")){
// The user confirmed it, so uncheck it
return true;
}else{
// Otherwise, keep it checked
element.checked = true;
}
}
}
示例强>
<div id="ChkBox">
<input style="margin: 5px; " type="checkbox" name="chkIsActive" onchange="Areyousure(this)" value="example" checked />Is Active
</div>
<script>
function Areyousure(element) {
// If it is checked now, let it be
if (element.checked) {
return false;
// Otherwise prompt the user
} else {
// Prompt the user to make sure
if (confirm("Are you sure you want to Uncheck this?")){
// The user confirmed it, so uncheck it
return true;
}else{
// Otherwise, keep it checked
element.checked = true;
}
}
}
</script>
&#13;
答案 1 :(得分:0)
您的方法需要一个ID,但没有传入:
添加到您的输入:
<input id="chkIsActive"
并将脚本更改为调用方法:
<script>
Areyousure("chkIsActive");
</script>
答案 2 :(得分:0)
由于您是通过id(未定义)找到元素,因此javascript将无法找到html元素。
相反,您可以将输入标记编辑为类似的内容;
public boolean displayWord()
{
corLetters = 0; // <---- You should add this line here
boolean goodGuess = false;automatically
char letter = guessedLetter.charAt(0);
for(int i = 0;i<word.length();i++)
if (lettersFound[i]==true)
{
System.out.print(word.charAt(i)+" ");
corLetters++;
}
else if (word.charAt(i)==letter)
{
System.out.print(word.charAt(i)+" ");
lettersFound[i] = true;
goodGuess = true;
corLetters++;
}
else
System.out.print("_ ");
return goodGuess;
}
然后不是通过Id获取元素,而是可以使用以下命令获取它:
<input style="margin: 5px; " type="checkbox" name="chkIsActive" onchange="Areyousure()" value="@Model.Pharmacy.IsActive" @(Model.Pharmacy.IsActive =="True" ? "checked=\"checked\"" : "") />
您还需要更改功能,因为现在没有参数传递给函数。 干杯:)