我想知道该复选框是否被选中。有一个链接到该复选框的自定义验证器。使用java脚本,我检查复选框是否被选中
这是 ASpx 代码和 Java 脚本
function checkAcceptance(source, args) {
args.IsValid = document.getElementById('CheckBox1').checked;
}
<div>
<p>
<asp:CheckBox ID="CheckBox1" runat="server" meta:resourcekey="CheckBox1Resource1"></asp:CheckBox>
<asp:Literal ID="litTC1" runat="server" meta:resourcekey="litTC1Resource1" Text="I accept the"></asp:Literal>
<asp:HyperLink ID="CnC" runat="server" Target="_blank" meta:resourcekey="CnCResource1">Condition of Carriage</asp:HyperLink>
<asp:CustomValidator ID="cvTermsConditions" runat="server" ClientValidationFunction="checkAcceptance" ErrorMessage="Terms and Conditions must be accepted" meta:resourcekey="cvTermsConditionsResource1" Text="*"></asp:CustomValidator>
</p>
</div>
这是怎么回事
最佳答案
您需要找到该元素,因为母版页会更改您的 ID。
我建议您使用 JQuery,但如果没有,请尝试使用:
function checkAcceptance(source, args) {
var idcheckbox = document.querySelector("[id*='CheckBox1']").id;
args.IsValid = document.getElementById(idcheckbox).checked;
}
或者也许您想尝试一下,尝试使用不同的选择器(CSS 方法)
http://www.w3schools.com/jsref/met_document_queryselector.asp
更新:
使用JQuery方法:
将 JQuery 脚本导入到您的母版页。 使用:
<asp:CheckBox ID="CheckBox1" runat="server" meta:resourcekey="CheckBox1Resource1" class="myclass"></asp:CheckBox>
和 JavaScript:
args.IsValid = $(".myclass").prop("checked");
关于javascript - 复选框 document.getElementById 获取 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35690687/