[英]Javascript Checkbox Ticked on Load Error
I have a .cshtml page that I'm going to set up with several checkboxes. 我有一个.cshtml页面,我将使用几个复选框进行设置。
The checkboxes should be checked/unchecked depending on the values of several variables passed into the view using the TempData. 复选框应根据使用TempData传递到视图中的多个变量的值来选中/取消选中。
I've set up the code as follows: 我将代码设置如下:
<script>
@if (TempData["enabled"] == "True") {
var eCheckBox = document.getElementById(eCheck);
eCheckBox.checked = true;
}
</script>
<h2>Update @TempData["fullName"]</h2>
<input type="checkbox" name="enabledCheckbox" value="Enabled" id="eCheck"/>Enabled<br/>
But the line 但是线
eCheckBox.checked = true;
produces the error 'identifier expected;checked is a keyword'. 产生错误“预期的标识符;已检查为关键字”。 Is there something obvious I'm missing?
有什么明显的我想念的东西吗? Making a checkbox ticked on load seems like it should be simple to do.
勾选复选框在加载时似乎很简单。
EDIT: I tried to correct the code as follows: 编辑:我试图更正代码,如下所示:
<input type="checkbox" name="enabledCheckbox" value="Enabled" id="eCheck" onload="checkTrue()"/>Enabled<br/>
<script type="text/javascript">
function checkTrue() {
alert("Here!");
if (TempData["enabled"] == "True") {
document.querySelector('[name=enabledCheckbox]').checked = true;
}
}
</script>
It doesn't look as though the code is hitting the function at all, as no alert fires. 看起来好像代码根本没有达到该功能,因为没有警报触发。
You miss to retrieve your HTML element correctly through JS. 您错过了通过JS正确检索HTML元素的机会。 Just use this:
只需使用此:
document.querySelector('[name=enabledCheckbox]').checked = true;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.