I have a GridView in which there are two columns of checkboxes i want to add two seperate "check all" text boxes at the top, "check all" above column A should check all the checkboxes in that column only. "check all" above column B should check all the columns in column B only. Also i am not able to apply groupvalidation. For every row only one of the two columns should get selected. I tried finding solution but when i click on check all at the top it checks all the checkboxes present in the gridview and also there is no group validation. Here is my Code..
HEAD:
<script type = "text/javascript">
function Check_Click(objRef) {
//Get the Row based on checkbox
var row = objRef.parentNode.parentNode;
if (objRef.checked) {
//If checked change color to Aqua
row.style.backgroundColor = "aqua";
}
else {
//If not checked change back to original color
if (row.rowIndex % 2 == 0) {
//Alternating Row Color
row.style.backgroundColor = "#C2D69B";
}
else {
row.style.backgroundColor = "white";
}
}
//Get the reference of GridView
var GridView = row.parentNode;
//Get all input elements in Gridview
var inputList = GridView.getElementsByTagName("input");
for (var i = 0; i < inputList.length; i++) {
//The First element is the Header Checkbox
var headerCheckBox = inputList[0];
//Based on all or none checkboxes
//are checked check/uncheck Header Checkbox
var checked = true;
if (inputList[i].type == "checkbox" && inputList[i] != headerCheckBox) {
if (!inputList[i].checked) {
checked = false;
break;
}
}
}
headerCheckBox.checked = checked;
}
</script>
<script type = "text/javascript">
function checkAll(objRef) {
var GridView = objRef.parentNode.parentNode.parentNode;
var inputList = GridView.getElementsByTagName("input");
for (var i = 0; i < inputList.length; i++) {
//Get the Cell To find out ColumnIndex
var row = inputList[i].parentNode.parentNode;
if (inputList[i].type == "checkbox" && objRef != inputList[i]) {
if (objRef.checked) {
//If the header checkbox is checked
//check all checkboxes
//and highlight all rows
row.style.backgroundColor = "aqua";
inputList[i].checked = true;
}
else {
//If the header checkbox is checked
//uncheck all checkboxes
//and change rowcolor back to original
if (row.rowIndex % 2 == 0) {
//Alternating Row Color
row.style.backgroundColor = "#C2D69B";
}
else {
row.style.backgroundColor = "white";
}
inputList[i].checked = false;
}
}
}
}
</script>
BODY:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="RollNo" HeaderText="RollNo" />
<asp:TemplateField HeaderText="Date">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtender1" runat="server"
TargetControlID="TextBox1">
</asp:CalendarExtender>
</EditItemTemplate>
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><asp:CalendarExtender ID="CalendarExtender2"
runat="server" TargetControlID="TextBox2">
</asp:CalendarExtender>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Time" />
<asp:TemplateField HeaderText="Absent">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" Text="Absent" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Present">
<HeaderTemplate>
<asp:CheckBox ID="checkAll" runat="server" onclick = "checkAll(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" Text="Present"
onclick = "Check_Click(this)" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Ok i found solution to my problem. Although there is still one glitch.
Head:
<div runat="server">
<script type="text/javascript">
function SelectAll(id) {
//get reference of GridView control
var grid = document.getElementById("<%= GridView1.ClientID %>");
//variable to contain the cell of the grid
var cell;
if (grid.rows.length > 0) {
//loop starts from 1. rows[0] points to the header.
for (i = 1; i < grid.rows.length; i++) {
//get the reference of first column
cell = grid.rows[i].cells[4];
//loop according to the number of childNodes in the cell
for (j = 0; j < cell.childNodes.length; j++) {
//if childNode type is CheckBox
if (cell.childNodes[j].type == "checkbox") {
//assign the status of the Select All checkbox to the cell checkbox within the grid
cell.childNodes[j].checked = document.getElementById(id).checked;
}
}
}
}
}
function SelectAll1(id) {
//get reference of GridView control
var grid = document.getElementById("<%= GridView1.ClientID %>");
//variable to contain the cell of the grid
var cell;
if (grid.rows.length > 0) {
//loop starts from 1. rows[0] points to the header.
for (i = 1; i < grid.rows.length; i++) {
//get the reference of first column
cell = grid.rows[i].cells[3];
//loop according to the number of childNodes in the cell
for (j = 0; j < cell.childNodes.length; j++) {
//if childNode type is CheckBox
if (cell.childNodes[j].type == "checkbox") {
//assign the status of the Select All checkbox to the cell checkbox within the grid
cell.childNodes[j].checked = document.getElementById(id).checked;
}
}
}
}
}
</script>
<script type = "text/javascript">
function CheckBoxCheck(rb) {
var gv = document.getElementById("<%=GridView1.ClientID%>");
var row = rb.parentNode.parentNode;
var rbs = row.getElementsByTagName("input");
for (var i = 0; i < rbs.length; i++) {
if (rbs[i].type == "checkbox") {
if (rbs[i].checked && rbs[i] != rb) {
rbs[i].checked = false;
break;
}
}
}
}
</script>
</div>
Body:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="RollNo" HeaderText="RollNo" />
<asp:TemplateField HeaderText="Date">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtender1" runat="server"
TargetControlID="TextBox1">
</asp:CalendarExtender>
</EditItemTemplate>
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><asp:CalendarExtender ID="CalendarExtender2"
runat="server" TargetControlID="TextBox2">
</asp:CalendarExtender>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Time" />
<asp:TemplateField HeaderText="Present">
<AlternatingItemTemplate>
<asp:CheckBox ID="cbSelectAll1" runat="server" onclick="CheckBoxCheck(this)" />
</AlternatingItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="cbSelectAll1" runat="server" Text="All Absent"
onclick="CheckBoxCheck(this)" AutoPostBack="True" ValidationGroup="a" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbSelectAll1" runat="server" onclick="CheckBoxCheck(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<AlternatingItemTemplate>
<asp:CheckBox ID="cbSelectAll" runat="server" onclick="CheckBoxCheck(this)"/>
</AlternatingItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="cbSelectAll" runat="server" Text="All Present"
onclick="CheckBoxCheck(this)" AutoPostBack="True" ValidationGroup="a" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="cbSelectAll" runat="server" onclick="CheckBoxCheck(this)" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CODE BEHIND:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
//Find the checkbox control in header and add an attribute
((CheckBox)e.Row.FindControl("cbSelectAll")).Attributes.Add("onclick", "javascript:SelectAll('" + ((CheckBox)e.Row.FindControl("cbSelectAll")).ClientID + "')");
((CheckBox)e.Row.FindControl("cbSelectAll1")).Attributes.Add("onclick", "javascript:SelectAll1('" + ((CheckBox)e.Row.FindControl("cbSelectAll1")).ClientID + "')");
}
}
The glitch is that user can still select both the "check all" and therefore both the columns get selected at the same time. Athough only one can be selected when not using select all check box.
Related
I have a GridView that displays records that are either the number 1 or 0.
How can I convert the record into a check box which is checked if the value is 1 or unchecked if the value is 0?
<asp:GridView ID="gvStations" runat="server">
<columns>
<asp:templatefield headertext="Type" sortexpression="TypeDesc">
<edititemtemplate>
<asp:CheckBox ID="cbTypeEdit" runat="server" Text='<%# Bind("TypeDesc") />
</edititemtemplate>
<itemtemplate>
<asp:CheckBox ID="cbType" runat="server" Text='<%# Bind("TypeDesc") ></asp:CheckBox>
</itemtemplate>
<itemstyle horizontalalign="Center" />
</asp:templatefield>
<asp:templatefield headertext="Type 2" sortexpression="TypeDesc2">
<edititemtemplate>
<asp:CheckBox ID="cbType2Edit" runat="server" Text='<%# Bind("TypeDesc2") />
</edititemtemplate>
<itemtemplate>
<asp:CheckBox ID="cbType2" runat="server" Text='<%# Bind("TypeDesc2") ></asp:CheckBox>
</itemtemplate>
<itemstyle horizontalalign="Center" />
</asp:templatefield>
</columns>
</asp:GridView>
Right now I can change them to an X if its a 1 and a "blank" if its a 0.
protected void gvStations_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int i = 0; i <= this.gvStations.Rows.Count - 1; i++)//from here down changes the 1's to X's and O's to blanks.
{
for (int j = 0; j <= this.gvStations.Columns.Count - 1; j++)
{
if (j != 1 && j != 2)
{
if (this.gvStations.Rows[i].Cells[j].Text == "1")
{
this.gvStations.Rows[i].Cells[j].Text = "X";
}
else if (this.gvStations.Rows[i].Cells[j].Text == "0")
{
this.gvStations.Rows[i].Cells[j].Text = " ";
}
}
}
}
}
For display you can go as simple as a single comparison of the binded value:
<asp:CheckBox ID="cbTypeEdit" runat="server"
Checked='<%# (int)Eval("TypeDesc") == 1 %>'/>
For handling editing of the grid row I am afraid you need to handle the GridView's RowUpdated event and convert the values manually.
I think that should be:
<asp:CheckBox ID="cbTypeEdit" runat="server" Text='<%# Bind("TypeDesc") %>' Checked="<%# (Int)Eval("TypeDesc") == 0 ? false : true %>" />
A simple helper function would be better as you have TypeDesc and TypeDesc2.
Markup
Checked='<%# SetCheckedStatus(Bind("TypeDesc")) %>'
Checked='<%# SetCheckedStatus(Bind("TypeDesc2")) %>'
Code-behind
protected bool SetCheckedStatus(object typeDesc)
{
var isChecked = false;
var intValue = 0;
if (typeDesc != null)
{
int.TryParse(typeDesc.ToString(), out intValue);
if (intValue == 1) { isChecked = true; }
}
return isChecked;
}
Much cleaner markup this way
Hello i have a gridview Naming FolderGridView. in the GridView There is a template field and inside the template field i am specifying a Linkbutton. Now i cannot get values from the linkButton in my codeBehind.
<asp:GridView ID="FolderGridView" runat="server"
AutoGenerateColumns = "False"
AllowPaging ="True" OnPageIndexChanging ="FolderGridView_PageIndexChanging" CellPadding="4" ForeColor="#333333" GridLines="None"
>
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="FolderCheckBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Folder Name">
<ItemTemplate>
<asp:LinkButton Text='<%#Eval("File Name")%>' PostBackUrl='<%# String.Format("InsideFolder.aspx?FolderName={0}", Eval("File Name") ) %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
my code Behind
for (int i = 0; i < FolderGridView.Rows.Count; i++)
{
CheckBox chk = (CheckBox)FolderGridView.Rows[i].FindControl("FolderCheckBox");
if (chk.Checked == true)
{
string FileName = (string)FolderGridView.Rows[i].Cells[1].Text.ToString();
}
}
I have debugged the code behind portion. In FileName i get an empty string when i get to this point. How to get values from the template field then?
The text in the cell is inside the LinkButton control, so first you have to get the LinkButton control of the GridView row, and then you can access the Text property. The following code should work in your case:
for (int i = 0; i < FolderGridView.Rows.Count; i++){
CheckBox chk = (CheckBox)FolderGridView.Rows[i].FindControl("FolderCheckBox");
if (chk.Checked == true){
foreach (Control ctl in FolderGridView.Rows(i).Cells(1).Controls) {
if (ctl is LinkButton) {
string filename = ((LinkButton)ctl).Text;
}
}
}
replace Link Button with
EDIT:
For LinkButton:
<asp:LinkButton ID="LinkButton1" AutoPostBack="True" OnClick="someMethod" Text='<%#Eval("File Name")%>' PostBackUrl='<%# String.Format("InsideFolder.aspx?FolderName={0}", Eval("File Name") ) %>' runat="server" />
and code Behind
protected void someMethod(object sender, EventArgs e)
{
foreach (GridViewRow item in GridView5.Rows)
{
CheckBox chk = (CheckBox)item.FindControl("FolderCheckBox");
if (chk.Checked == true)
{
string probname = chk.Text;
}
}
}
I Have some Problem in Hiding Rows of Gridview Using Javascript...
My Js Function is
<script type="text/javascript">
function HideRows(Gdview) {
rows = document.getElementById(Gdview).rows;
for (var i = 0; i < rows.length; i++) {
if (rows[i].cells[0].type == "checkbox") {
if (rows[i].cells[0].childNodes[0].checked) {
rows[i].style.display = "none";
}
}
}
}
</script>
I Have a Gridview ID="Gdview" Which has 5 Columns and Every Column has a checkbox with id="Chk" and i placed a Button after the Gridview(Button id="Btn") i wannt to hide the Selected rows using checkboxes..i tried the following code behind..but it is not working..what wud be the problem?? IS this Wrong Way????
protected void Btn_Click1(object sender, EventArgs e)
{
Btn.Attributes.Add("onclick", "HideRows('" + Gdview + "')");
}
2ND Question Likewise same as first one:
Here i am trying to select and unselect all checkboxes in gridview using respective link buttons...See my markup and JS:
<script type="text/javascript">
function SelectAll(b) {
var grid = document.getElementById("<%= Gdview.ClientID %>");
var cell;
if (grid.rows.length > 0) {
for (var i = 0; i < grid.rows.length; i++) {
cell = grid.rows[i].cells[0];
if (cell.childNodes[0].type == "checkbox")
cell.childNodes[0].checked = b;
}
}
}
</script>
<asp:GridView ID="Gdview" runat="server" AutoGenerateColumns="False"
onrowdatabound="Gdview_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="Chk" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="SNO" DataField="SerialNo" />
<asp:BoundField HeaderText="Organization" DataField="Organization" />
<asp:BoundField DataField="Origin" HeaderText="Origin"/>
<asp:BoundField DataField="Location" HeaderText="Location" />
<asp:BoundField DataField="Established" HeaderText="Established"/>
<asp:TemplateField>
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:LinkButton ID="lnkChekall" runat="server" Text="Chekall"></asp:LinkButton>
<asp:LinkButton ID="lnkUncheck" runat="server" Text="UnCheckAll"></asp:LinkButton>
and i added Rowdatabound event in codebehind:
protected void Gdview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
lnkChekall.Attributes.Add("onclick","javascript:SelectAll('" +"true" +"')");
lnkUncheck.Attributes.Add("onclick", "javascript:SelectAll('" + "false" +"')");
}
}
it is not working guys plz help me in my problems with the Javascripts...
EDIT 3
In your second question, I can see there are few problems:
You should not add attribute in RowDataBound. It would add the
attribute for each row instead of only once.
Your javascript is wrong.
You should pass boolean true/false to javascript function, not
string.
To make it work, Add the attributes at Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//PopulateGridView
PopulateGrid();
}
lnkChekall.Attributes.Add("onclick", "javascript:SelectAll(true)");
lnkUncheck.Attributes.Add("onclick", "javascript:SelectAll(false )");
}
And change your javascript to this:
<script type="text/javascript">
function SelectAll(b) {
var grid = document.getElementById("<%= Gdview.ClientID %>");
var cell;
if (grid.rows.length > 0) {
for (var i = 0; i < grid.rows.length; i++) {
cell = grid.rows[i].getElementsByTagName("input");
if (cell.length > 0) {
cell[0].checked = b;
}
}
}
}
</script>
You are doing it wrong way! There's no need to call JS from code behind. Just add style to make the row invisible. Here's how I would do it:
In the markup I have my GridView with five check boxes and one row number (Just to populate the Gridview with data). I also have a button :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField HeaderText="CheckBox 1">
<ItemTemplate>
<asp:CheckBox ID="chk1" Text="CheckBox 1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CheckBox 2">
<ItemTemplate>
<asp:CheckBox ID="chk2" Text="CheckBox 2" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CheckBox 3">
<ItemTemplate>
<asp:CheckBox ID="chk3" Text="CheckBox 3" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CheckBox 4">
<ItemTemplate>
<asp:CheckBox ID="chk4" Text="CheckBox 4" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CheckBox 5">
<ItemTemplate>
<asp:CheckBox ID="chk5" Text="CheckBox 5" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Row">
<ItemTemplate>
<%#Container.DataItem %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Btn" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
Now in the code I am populating the GridView with test data. In the button's click event I am looping through all rows of GridView and finding the first CheckBox. If it is checked, I am hiding the row:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Test Data
var lst = new List<string>() { "Row 1", "Row 2", "Row 3" };
GridView1.DataSource = lst;
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
var chk = row.FindControl("chk1") as CheckBox;
if (chk != null && chk.Checked)
{
row.Attributes.Add("style", "display:none");
}
}
}
EDIT : If you want to use javascript, still there's no need to assign it from code behind. Add an input to the markup to call js HideRows() function:
<asp:Button ID="Btn" runat="server" Text="Button" OnClick="Button1_Click" />
And the function in the page should look like this:
<script type="text/javascript" >
function HideRows(Gdview) {
var rows = document.getElementById(Gdview).rows;
for( var i=0; i < rows.length; i++ ) {
var inputs = rows[i].getElementsByTagName("input");
if (inputs.length > 0 && inputs[0].checked) {
rows[i].style.display = "none";
}
}
}
</script>
Here's the screenshot before and after clicking the button:
You can download my test project here.
EDIT 2 : If you need to call the function from code behind, just do this:
protected void Button1_Click(object sender, EventArgs e)
{
//Your other code goes here
//
Page.ClientScript.RegisterStartupScript(GetType(), "HideRows", "HideRows('" + GridView1.ClientID + "');", true);
}
client Id of server control is different from the Id you assigned, so try:
document.getElementById("<%= Gdview .ClientID %>")
complete code:
//dont pass as parameter
function HideRows() {
rows = document.getElementById("<%= Gdview.ClientID %>").rows;
for (var i = 0; i < rows.length; i++) {
if (rows[i].cells[0].type == "checkbox") {
if (rows[i].cells[0].childNodes[0].checked) {
rows[i].style.display = "none";
}
}
}
}
I have gridview, I want to do a foreach on it's rows and get the value from column's header where there's a Label for one cell from this row.
foreach (GridViewRow mainRow in grid1.Rows)
{
var header = mainRow.Cells[2].Parent.FindControl("LabelID");//is null
}
How do I find it ?
If you want the value in RowDataBound event then you can check RowType like this
if(e.Row.RowType == DataControlRowType.Header)
{
Label header = (Label)e.Row.FindControl("LabelID");
}
I would access the headerRow and enumerate through the according cells (on buttonClick or on RowDataBound ...)
default.aspx
<asp:GridView AutoGenerateColumns="false" ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="headerLabel1" runat="server" Text="Headercolumn1"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="itemLabel1" runat="server" Text='<%# Eval("name") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnGetHeader" runat="server" Text="GetHeader" OnClick="btnGetHeader_Click" />
default.aspx.cs
protected void btnGetHeader_Click(object sender, EventArgs e)
{
foreach (TableCell headerCell in GridView1.HeaderRow.Cells)
{
// or access Controls with index
// headerCell.Controls[INDEX]
Label lblHeader = headerCell.FindControl("headerLabel1") as Label;
if (lblHeader != null)
Debug.WriteLine("lblHeader: " + lblHeader.Text);
}
}
I am using javascript to make unchecked GridView .
But whenever I try, I cannot make unchecked it.
function UncheckedItemsCheckBox(CheckboxID) {
var checkbox = document.getElementById(CheckboxID);
checkbox.checked = false;
alert(checkbox.id + " : " + checkbox.name + " : " + checkbox.checked);
}
Here is the output.
---------------------------
Message from webpage
---------------------------
GridView1_ctl02_txtDoseQty : GridView1$ctl02$txtDoseQty : false
---------------------------
OK
---------------------------
Even though "checkbox.checked" return me "false" as output message shown, but at the gridview checkbox is still checked.
Could anyone please give me suggestion?
What may be happening is that your CheckBoxID is wrong, and therefore returning the wrong element.
In JavaScript, saying checkbox.checked = false; will, if this object did not previously have a checked property, add one to the object, with the value provided. So, if your CheckBoxID is in fact wrong, it's no surprise your alert shows false; any non-null element you pull back with getElementById will allow you to add a checked property to it.
More specifically, in asp.net when you create a checkbox column, like this
<asp:CheckBoxField Text="Hello" DataField="foo" />
it renders html like this:
<span class="aspNetDisabled">
<input id="gv_ctl00_0" type="checkbox" name="gv$ctl02$ctl00" disabled="disabled">
<label for="gv_ctl00_0">Hello</label>
</span>
A couple possibilities:
The id you're getting may be of the span, on which you're adding a checked property.
You're setting the checkbox to be checked, but since it's disabled, it's not updating its state -- ok, it looks like disabled checkboxes can have their checked properties updated. Hopefully #1 is your problem.
A good place to start debugging would be to change your function to this
function UncheckedItemsCheckBox(CheckboxID) {
var checkbox = document.getElementById(CheckboxID);
alert(checkbox.checked); // <------- should display false, but will
// display undefined if this element is
// something other than a checkbox
checkbox.checked = false;
alert(checkbox.id + " : " + checkbox.name + " : " + checkbox.checked);
}
Are you trying to check or uncheck the checkboxes in a GridView.
If yes then you can try this simple code.
Here we have the javascript function which will called , when the header checkbox is clicked
<script type="text/javascript">
function Check_All(ChkBoxHeader)
{
//First Access the GridView Control
var gridview = document.getElementById('<%=GridEmployees.ClientID %>');
//Now get the all the Input type elements in the GridView
var AllInputsElements = gridview.getElementsByTagName('input');
var TotalInputs = AllInputsElements.length;
//Now we have to find the checkboxes in the rows.
for(var i=0;i< TotalInputs ; i++ )
{
if(AllInputsElements[i].type =='checkbox')
{
AllInputsElements[i].checked = ChkBoxHeader.checked;
}
}
}
The GridView will look like this
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="checkRecords" runat="server" />
</ItemTemplate>
<HeaderTemplate>
<asp:CheckBox ID="CheckHeader" runat="server" onclick="Check_All(this);" />
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I hope that this will help you.
Javascript for Check and uncheck the Checkboxes in gridView
<script language="javascript" type="text/javascript">
var TotalChkBx;
var Counter;
var TotalUnChkBx;
var UnCounter;
window.onload = function () {
//Get total no. of CheckBoxes in side the GridView.
TotalChkBx = parseInt('<%= this.GridView1.Rows.Count %>');
//Get total no. of checked CheckBoxes in side the GridView.
Counter = 0;
}
function HeaderClick(CheckBox) {
//Get target base & child control.
var TargetBaseControl = document.getElementById('<%= this.GridView1.ClientID %>');
var TargetChildControl = "chkBxSelect";
//Get all the control of the type INPUT in the base control.
var Inputs = TargetBaseControl.getElementsByTagName("input");
//Checked/Unchecked all the checkBoxes in side the GridView.
for (var n = 0; n < Inputs.length; ++n)
if (Inputs[n].type == 'checkbox' && Inputs[n].id.indexOf(TargetChildControl, 0) >= 0)
Inputs[n].checked = CheckBox.checked;
//Reset Counter
Counter = CheckBox.checked ? TotalChkBx : 0;
}
function ChildClick(CheckBox, HCheckBox) {
//get target base & child control.
var HeaderCheckBox = document.getElementById(HCheckBox);
//Modifiy Counter;
if (CheckBox.checked && Counter < TotalChkBx)
Counter++;
else if (Counter > 0)
Counter--;
//Change state of the header CheckBox.
if (Counter < TotalChkBx)
HeaderCheckBox.checked = false;
else if (Counter == TotalChkBx)
HeaderCheckBox.checked = true;
}
</script>
In GridView
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
AlternatingRowStyle-BackColor="#006699"
AlternatingRowStyle-ForeColor="#FFFFFF"
>
<Columns >
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkBxSelect" runat="server" />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="50px" />
<HeaderTemplate>
<asp:CheckBox ID="chkBxHeader" onclick="javascript:HeaderClick(this);" runat="server" />
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Serial Number">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Name" DataField="uname" />
<asp:BoundField HeaderText="Pass" DataField="upass"/>
</Columns>
</asp:GridView>
Try this One
$(document).ready(function () {
$("#headercheck").click(function () {
var ischecked;
if (this.checked == true) {
ischecked = true;
}
else {
ischecked = false;
}
$('<%="#"+GridViewClass1.ClientID%> input:checkbox').attr('checked', $(this).is(':checked'))
});
});
headercheck is my chcekboxid.
I have used something like this to check and uncheck the checkbox in my code. Hope it helps you.
<script language="javascript" type="text/javascript">
// function Search()
// {
// alert("hi");
// }
function SearchValidation() {
var str = "";
var flag;
var count = 0;
// alert("Hi");'txtFirstName'
if (document.getElementById('<%=ddlProjectName.ClientID%>').selectedIndex == 0) {
str += "Select project name \n";
flag = false;
count++;
// alert(count);
}
if (document.getElementById('<%=ddlUsers.ClientID%>').selectedIndex == 0) {
str += "Select project name \n";
flag = false;
count++;
}
if (document.getElementById('<%=ddlEmployee.ClientID%>').selectedIndex == 0) {
str += "Select project name \n";
flag = false;
count++;
}
if (document.getElementById('<%=txtFromDate.ClientID%>').value == "") {
str += "Enter Fromdate \n";
flag = false;
count++;
}
else {
var input = document.getElementById('<%=txtFromDate.ClientID%>');
var validformat = /\d{2}\/\d{2}\/\d{4}$/;
if (!validformat.test(input.value)) {
str += "Invalid Fromdate Format. Please correct and submit again. \n";
flag = false;
}
else {
}
}
if (document.getElementById('<%=txtToDate.ClientID%>').value == "") {
str += "Enter Todate \n";
flag = false;
count++;
}
else {
var inputTo = document.getElementById('<%=txtToDate.ClientID%>');
var validTo = /\d{2}\/\d{2}\/\d{4}$/;
if (!validTo.test(inputTo.value)) {
str += "Invalid Todate Format. Please correct and submit again. \n";
flag = false;
}
else {
}
}
if (count == 5) {
alert("Select any one search criteria.");
return false;
}
else {
return true;
}
}
function ExportToExcelValidation() {
var str = "";
var flag;
// alert("Hi");'txtFirstName'
if (document.getElementById('<%=ddlProjectName.ClientID%>').selectedIndex == 0) {
str += "Select project name \n";
flag = false;
}
if (document.getElementById('<%=txtFromDate.ClientID%>').value == "") {
str += "Enter Fromdate \n";
flag = false;
}
else {
var input = document.getElementById('<%=txtFromDate.ClientID%>');
var validformat = /\d{2}\/\d{2}\/\d{4}$/;
if (!validformat.test(input.value)) {
str += "Invalid Fromdate Format. Please correct and submit again. \n";
flag = false;
}
}
if (document.getElementById('<%=txtToDate.ClientID%>').value == "") {
str += "Enter Todate \n";
flag = false;
}
else {
var inputTo = document.getElementById('<%=txtToDate.ClientID%>');
var validTo = /\d{2}\/\d{2}\/\d{4}$/;
if (!validTo.test(inputTo.value)) {
str += "Invalid Todate Format. Please correct and submit again. \n";
flag = false;
}
}
if (flag == false) {
alert(str);
return flag;
}
else {
return flag;
}
}
function CheckValidation() {
if (confirm("Are you sure you want to delete this ?"))
return true;
else
return false;
}
function CheckAll(oCheckbox) {
var GridView2 = document.getElementById("<%=gvLeads.ClientID %>");
for (i = 1; i < GridView2.rows.length; i++) {
GridView2.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked = oCheckbox.checked;
// alert(GridView2.rows[i].cells[0].getElementsByTagName("INPUT")[0]);
}
}
function CheckIndividual(oCheck) {
var GridView2 = document.getElementById("<%=gvLeads.ClientID %>");
var checkedCount = 0;
for (i = 1; i < GridView2.rows.length; i++) {
if (GridView2.rows[i].cells[0].getElementsByTagName("INPUT")[0].checked == true) {
checkedCount++;
}
}
if (checkedCount == GridView2.rows.length - 1) {
GridView2.rows[0].cells[0].getElementsByTagName("INPUT")[0].checked = oCheck.checked;
}
else {
GridView2.rows[0].cells[0].getElementsByTagName("INPUT")[0].checked = false;
}
}
</script>
<%----%>
<%-- --%>
' runat="server" Visible="false" />
' runat="server" Visible="false" />
' runat="server" Visible="false" />
<%--onclick="fnCheckAll(this);"--%>
<%--
' runat="server" Visible="false"/>
</ItemTemplate>
</asp:TemplateField>--%>
<%-- <asp:TemplateField HeaderText="Project Id">
<ItemTemplate>
<asp:Label ID="lblProjectId" Text='<%#Eval("ProjectId") %>' runat="server" Visible="false"/>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Project Name">
<ItemTemplate>
<asp:Label ID="lblProjectName" Text='<%#Eval("ProjectName") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Lead Name">
<ItemTemplate>
<asp:Label ID="lblLeadName" Text='<%#Eval("LeadName") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Employee Name">
<ItemTemplate>
<asp:Label ID="lblEmployeeName" Text='<%#Eval("EmployeeName") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<%-- <asp:TemplateField HeaderText="Lead Id">
<ItemTemplate>
<asp:Label ID="lblAddedUserName" Text='<%#Eval("LeadId") %>' runat="server" Visible="false"/>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="From Date">
<ItemTemplate>
<asp:Label ID="lblFromDate" Text='<%#Eval("FromDate") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="To Date">
<ItemTemplate>
<asp:Label ID="lblToDate" Text='<%#Eval("ToDate") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Added UserName">
<ItemTemplate>
<asp:Label ID="lblCreatedBy" Text='<%#Eval("CreatedBy") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Created Date">
<ItemTemplate>
<asp:Label ID="lblCreatedDate" Text='<%#Eval("CreatedDate") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
<%--<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Label ID="lblLeadId" Text='<%#Eval("LeadId") %>' runat="server" Visible="false" />
<asp:Label ID="lblProjectId" Text='<%#Eval("ProjectId") %>' runat="server" Visible="false" />
<asp:Label ID="lblEmployeeId" Text='<%#Eval("EmployeeId") %>' runat="server" Visible="false" />
<asp:Label ID="lblEdit" Text='<%#Eval("Id") %>' runat="server" Visible="false" />
<asp:Button ID="btnEdit" runat="server" Text="Edit" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:Label ID="lblDelete" Text='<%#Eval("Id") %>' runat="server" Visible="false" />
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick="if(!CheckValidation())return false;" />
</ItemTemplate>
</asp:TemplateField>--%>
</Columns>
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<HeaderStyle BackColor="#9966FF" Font-Bold="True" ForeColor="#FFFFCC" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#330099" BorderColor="#0066CC" Font-Bold="False" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="False" ForeColor="#663399" />
<SortedAscendingCellStyle BackColor="#FEFCEB" />
<SortedAscendingHeaderStyle BackColor="#AF0101" />
<SortedDescendingCellStyle BackColor="#F6F0C0" />
<SortedDescendingHeaderStyle BackColor="#7E0000" />
</asp:GridView>