如何检查是否使用 JavaScript 检查了 GridView 中的复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21195004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if checkbox that is in GridView is checked using JavaScript
提问by moe
I have Checkbox and text-box inside a GRIDVIEW. If checkbox is not checked and the text-box has no comments, then I want to show a message that says please enter comments in the text-box. I don't want to show any message if all checkboxes are checked. I want to accomplish this by using a JavaScript so I have tried but I am not quite there yet and I had some issues all day with this. Please help. I am only checking the checkbox here and not the text-box and I am not sure how to check both the checkbox and the text-box so please help. Here is my JavaScript:
我在 GRIDVIEW 中有复选框和文本框。如果未选中复选框并且文本框没有评论,那么我想显示一条消息,说请在文本框中输入评论。如果选中所有复选框,我不想显示任何消息。我想通过使用 JavaScript 来实现这一点,所以我已经尝试过了,但我还没有完全到位,而且我整天都遇到了一些问题。请帮忙。我只在这里检查复选框而不是文本框,我不确定如何同时检查复选框和文本框,所以请帮忙。这是我的 JavaScript:
<script type="text/javascript">
function validate() {
var flag = true;
var checkbox = new Array();
var gridview = document.getElementById('<%=GridView1.ClientID%>');
checkbox = gridview.getElementsByTagName('myCheckbox');
for (var i = 0; i < checkbox.length; i++) {
if (checkbox.item(i).checked)
{
flag = false;
break;
}
}
if (!flag) {
alert('Please enter comments. Thanks');
}
return flag;
}
</script>
and here is my checkbox and the text-box in the aspx file
这是我的复选框和 aspx 文件中的文本框
<asp:TemplateField ItemStyle-Width="150px" HeaderText="Comments">
<ItemTemplate>
<asp:TextBox ID="txtComm" runat="server" TextMode="MultiLine" Width="130px" Height="50px" BackColor="LightGoldenrodYellow"
Text='<%# Eval("COMMENTS")%>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="15px" HeaderText="Approved?">
<ItemTemplate>
<asp:CheckBox ID="mycheckbox" runat="server" Checked='<%#Eval("APPR")==DBNull.Value? false:Eval("APPR") %>' />
</ItemTemplate>
</asp:TemplateField>
采纳答案by afzalulh
This should work: EDIT :Edited to reflect the requested change.
这应该有效: 编辑:编辑以反映请求的更改。
function validate() {
var flag = false;
var gridView = document.getElementById('<%= GridView1.ClientID %>');
for (var i = 1; i < gridView.rows.length; i++) {
var inputs = gridView.rows[i].getElementsByTagName('input');
var areas = gridView.rows[i].getElementsByTagName('textarea');
if (inputs != null && inputs.length > 1 && inputs[0] != null && areas != null && areas.length > 1 && areas[0] != null) {
if (areas[1].type == "textarea" && inputs[0].type == "checkbox") {
var txtval = areas[1].value;
if (!inputs[0].checked && (txtval == "" || txtval == null)) {
flag = false;
break;
}
else {
flag = true
}
}
}
}
if (!flag) {
alert('Please enter comments. Thanks');
}
return flag;
}