问题
I want to validate Gridview CheckBox Checked for Multiple Gridviews on the same page
I have tried the following but it is not working.
<script type="text/javascript">
var TargetBaseControl = null;
window.onload = function () {
try {
//get target base control.
TargetBaseControl = document.getElementById('<%= this.GridView1.ClientID%>', '<%= this.GridView2.ClientID%>');
}
catch (err) {
TargetBaseControl = null;
}
}
function TestCheckBox() {
if (TargetBaseControl == null) return false;
//get target child control.
var TargetChildControl = "chkSelectAdd";
//get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
for (var n = 0; n < Inputs.length; ++n)
if (Inputs[n].type == 'checkbox' &&
Inputs[n].id.indexOf(TargetChildControl, 0) >= 0 &&
Inputs[n].checked)
return true;
alert('Select at least one checkbox!');
return false;
}
</script>
回答1:
There are two problems that I can see here. document.getElementById only supports one element at a time, so your code will only check the first GridView's checkboxes. Also, an element's ID ought to be unique and so your check against the ID here:
Inputs[n].id.indexOf(TargetChildControl, 0) >= 0 &&
will only return true for the first checkbox.
I'd suggest removing the use of TargetBaseControl and simply relying on the names, rather than IDs, of the checkboxes instead:
var Inputs = document.getElementsByTagName("input");
for (var n = 0; n < Inputs.length; ++n)
if (Inputs[n].type == 'checkbox' &&
Inputs[n].name.indexOf(TargetChildControl, 0) >= 0 &&
Inputs[n].checked)
return true;
...
来源:https://stackoverflow.com/questions/25740354/validate-gridview-checkbox-checked-for-multiple-gridviews