3

I want to do a javascript function that check the unchecked checkbox. My function nowadays, check all the unchecked checkbox, and I need that just check a specific GridView unchecked checkbox

function checar() {    
    var el = document.getElementsByTagName("input");
    for (var i = 0; i < el.length; i++) {
        if (el[i].type == "checkbox") {
            el[i].checked = true;
        }
    }
}
Lucas_Santos
  • 4,638
  • 17
  • 71
  • 118

2 Answers2

2

You want to first limit the scope of your search for elements. One way to do so would be to use getElementById

function checar() { 
var grd = document.getElementById("<%=grd.ClientID%>"); // <-- Add this line
var el = grd.getElementsByTagName("input"); // <-- change the scope of this to grd
//rest of your code here.
}

Sample using divs, but you'll get the idea I think: http://jsfiddle.net/8LRkk/

Edited to include setting the specific Grid ID.

Doozer Blake
  • 7,677
  • 2
  • 29
  • 40
  • Yes, I saw it before I ask here, and I tried this solution, but the var grd, return null. – Lucas_Santos Oct 03 '11 at 16:51
  • Be sure that you are putting the actual Rendered ID of your GridView, not what is set in the code, example document.getElementById("<%=grd.ClientID%>"); – Doozer Blake Oct 03 '11 at 16:56
  • Not seeing your entire code, it's hard to say what's going on, but the above _should_ be working as you desire. Something is going on getting the ID of your grid view. – Doozer Blake Oct 03 '11 at 17:50
0

To get at all of the checkboxes of a particular gridview, you need to grab checkboxes whose ClientID contain the portion of the gridview's ClientID as well since all controls have an id which is "stacked".

Your function should work as a base, it just needs to have an added check in it:

function checar() {    
    var el = document.getElementsByTagName("input");

    // Get the client id of the gridview from ASP here
    var gvID = '<%= this.myGridview.ClientID %>';

    for (var i = 0; i < el.length; i++) {
        // Call the id of the checkbox and check to see if it
        // contains the client id of the gridview at the same time
        if (el[i].type == "checkbox" && el.id.indexOf(gvID) != -1) {
            el[i].checked = true;
        }
    }
}
Joel Etherton
  • 37,325
  • 10
  • 89
  • 104