Validate Gridview CheckBox Checked for Multiple Gridviews

巧了我就是萌 提交于 2019-12-13 05:18:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!