Find checkbox and textbox placed inside gridview using javascript - c#

I want to get the value of check box placed inside grid view. if check box is checked, it textbox in that row should be enable and if it is again uncheked, the textbox should get clear and disabled. I asked this question few hours back but still didn't get satisfactory answer.
I tried like this.
//My grid code.
<asp:GridView ID="DeptGrid" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="DeptId" HeaderText="ID"/>
<asp:BoundField DataField="DeptName" HeaderText="Department"/>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="addToCompanyBox" onClick="EnableHODBox()" runat="server" />
</ItemTemplate>
<HeaderTemplate>
Add
</HeaderTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="hodNameBox" runat="server" Width="200px" Enabled="false"></asp:TextBox>
</ItemTemplate>
<HeaderTemplate>
Dept Head
</HeaderTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
//My javascript code
<script type="text/javascript">
function EnableHODBox() {
//alert('hello');
var GridView = document.getElementById('<%=DeptGrid.ClientID %>');
//var GridView = document.getElementById('');
var DeptId;
if (GridView.rows.length > 0) {
for (Row = 1; Row < GridView.rows.length; Row++) {
// DeptId = GridView.rows.cell[0];
if (GridView.rows[Row].cell[3].type == "checkbox")
// var chkbox = GridView.rows[Row].cell[3].type == "checkbox"
(GridView.rows[Row].cell[3].type).checked = true;
}
}
}
</script>

This solution is tested and works using only JavaScript (no jQuery is required for this solution!).
1. C# Part (In Page_Load Method)
In Page_Load we need to add a small hack:
foreach(GridViewRow row in YourGridViewControlID.Rows)
{
if (row.RowType == DataControlRowType.DataRow )
{
((CheckBox) row.FindControl("YourCheckBoxID")).Attributes.Add("onchange", "javascript:TextboxAutoEnableAndDisable(" + (row.RowIndex ) + ");");
}
}
This way, we are adding the JavaScript function call on the OnChange event of every CheckBox of our GridView. What is special and we can't achieve through the HTML is that we are passing the Row Index of each one in the JavaScript function, something that we need later.
2. Some important notes for the HTML Part
Make sure that both Checkbox control and Textbox control but more importantly your GridView Control has static id by using the ClientIDMode="Static" as shown bellow:
<asp:CheckBox ID="YourCheckBoxID" runat="server" ClientIDMode="Static"/>
<asp:TextBox ID="YourTextBoxID" TextMode="SingleLine" runat="server" ClientIDMode="Static" />
And for the GridView control:
<asp:GridView ID="YourGridViewControlID" ...... ClientIDMode="Static" runat="server">
3. Javascript Part
And then in your JavaScript file/code:
function TextboxAutoEnableAndDisable(Row) {
// Get current "active" row of the GridView.
var GridView = document.getElementById('YourGridViewControlID');
var currentGridViewRow = GridView.rows[Row + 1];
// Get the two controls of our interest.
var rowTextBox = currentGridViewRow.cells[2].getElementsByTagName("input")[0];
var rowCheckbox = currentGridViewRow.cells[0].getElementsByTagName("input")[0];
// If the clicked checkbox is unchecked.
if( rowCheckbox.checked === false) {
// Empty textbox and make it disabled
rowTextBox.value = "";
rowTextBox.disabled = true;
return;
}
// To be here means the row checkbox is checked, therefore make it enabled.
rowTextBox.disabled = false;
}
4. Some Notes for the above implementation
Note that in the JavaScript code, at the line:
var currentGridViewRow = GridView.rows[Row + 1];
the [Row + 1] is important to make this work and should not change.
And finally:
The following lines:
var rowTextBox = currentGridViewRow.cells[2].getElementsByTagName("input")[0];
var rowCheckbox = currentGridViewRow.cells[0].getElementsByTagName("input")[0];
The .cells[2] and .cells[0] is maybe different for you, so you have to choose the correct number in the [].
Usually, this will be the column number of your GridView starting counting from 0.
So if your CheckBox was in the first column of the GridView then you need .cells[0].
If your TextBox is in the second column of your GridView then you need .cells[1] (in my case above, TextBox was in the third column of my GridView and therefore, I used .cells[2])

You can use the onclick JavaScript instead of the OncheckedChanged event which is a CheckBox server side event.
<asp:CheckBox ID="CheckBox2" runat="server" onclick="Javascript:JSfunctionName();" />
Edit:
var GridView = document.getElementById('<%=DeptGrid.ClientID %>')
Edit: Upon your request in comment
if (GridView.rows[Row].cell[2].type == "checkbox")
{
if (GridView.rows[Row].cell[2].childNodes[0].checked)
{
GridView.rows[Row].cell[3].childNodes[0].disabled=false;// Enable your control here
}
}

I also found that the statement if (GridView.rows[Row].cell[2].type == "checkbox") results in an error, GridView.rows[Row].cell[2].type is undefined. The code I have running now is as follows:
var grid = document.getElementById('<%=grdResults.ClientID%>');
if (grid.rows.length > 0) {
for (row = 1; row < grid.rows.length; row++) {
if (grid.rows[row].cells[0].childNodes[0].checked) {
// do something here
alert('function for row ' + row);
}
}

You can define your grid like this :
<div>
<asp:GridView ID="GridView1" runat="server" Width = "550px"
AutoGenerateColumns = "false" Font-Names = "Calibri"
Font-Size = "12pt" HeaderStyle-BackColor = "LightYellow" AllowPaging ="true" ShowFooter = "true" OnPageIndexChanging = "OnPaging" PageSize = "10" >
<Columns>
<asp:TemplateField ItemStyle-Width = "100px" HeaderText = "Name">
<ItemTemplate>
<asp:TextBox ID="txtPeriod" runat="server" CssClass="css1 mycss" Text='<%# Eval("Period")%>'
onblur="SetPostingPeriod(this)"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
</asp:GridView>
</div>
And your Javascript Function Would be :
<script language="javascript" type="text/javascript">
/* Populating same data to all the textboxes inside grid,
once change of text for one textbox - by using jquery
*/
function SetPostingPeriod(obj) {
var cntNbr = $("#" + obj.id).val();
// var cntNbr = document.getElementById(obj.id).value;
// alert(cntNbr);
//Access Grid element by using name selector
$("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {
if ($.trim($(this).val()) != "")
if (!isNaN($(this).val())) {
$(this).val(cntNbr);
}
});
}
</script>
This Javascript function is called onblur event of the textbox.
When this function is called at the same time it passes a parameter
which is nothing but the textbox id.
Inside javascript function by using the parameter which is the
id of the textbox we are getting the vaue.
Here is the code :
var cntNbr = $("#" + obj.id).val();
Then For each of the "txtPeriod" controls available inside the grid, we need to assign
the value of current "txtPeriod" textbox value to them.
Looping Grid to identify each "txtPeriod" available :
Here is the code :
$("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {
});
Inside this loop we need to assign the "txtPeriod"(current/Modified) value to other
"txtPeriod" textboxes.Before assign its good practice to check is it null or NAN.
Here is the code :
if ($.trim($(this).val()) != "")
if (!isNaN($(this).val())) {
$(this).val(cntNbr);
}

Hi here you are having very easy Solution
Suppose your grid is like this :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Height="64px"
Width="389px" EnableViewState="False">
<Columns>
<asp:TemplateField HeaderText="EmployeeId">
<ItemTemplate>
<asp:Label ID="lblEmployeeId" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FirstName">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LastName">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#FF66FF" ForeColor="#660033" />
</asp:GridView>
and your javascript to find controls inside your grid is
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#btnAddToGrid").click(function () {
var $grid = $('#<%=GridView1.ClientID %>');
var $row = $grid.find('tr:last').clone().appendTo($grid);
var employeeId = $row.find("span[id*='lblEmployeeId']").text();
var firstname = $row.find("span[id*='lblFirstName']").text();
var lastname = $row.find("span[id*='lblLastName']").text();
alert("ID :" + employeeId +"\n" + "Name :" + firstname +" "+ lastname );
});
});
</script>

Find controls inside the grid using java script:
for (var r = 1; r < grid.rows.length; ++r) {
var indexValue = 0; //based on browser. //IE8
var txtPeriod= grid.rows[r].cells[2].childNodes[indexValue];
if (typeof (txtPeriod.value) == "undefined")//IE9
indexValue = 1
var txtPeriod= grid.rows[r].cells[2].childNodes[indexValue];
alert(txtPeriod.value);
}

var x = document.getElementById('<%=grdResults.ClientID%>').querySelectorAll("input");
var i;
var cnt = 0;
for (i = 0; i < x.length; i++) {
if(x[i].type== "checkbox" && x[i].checked)
cnt++;
}
alert("item selected=" + cnt);

Related

How to Validate Drop-down inside GridView using JavaScript

I am trying to validate a drop down inside a gridview on a button click. If the drop down has no selection then i want to fire the javascript but the code is not firing at all. I am not sure what am i doing wrong here so please help. thanks.
Here is the button code in the aspx file:
<asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="183px" Visible="true"
onclick="btnSubmit_Click"
OnClientClick="return validate();"
Font-Bold="True" Font-Size="Medium" Height="30px"
style="margin-right: 1px; margin-left: 185px;" ForeColor="#336699" />
here is the javascript in the head section of my page:
<script type="text/javascript">
function validate() {
var flag = true;
var dropdowns = new Array(); //Create array to hold all the dropdown lists.
var gridview = document.getElementById('<%=GridView1.ClientID%>'); //GridView1 is the id of ur gridview.
dropdowns = gridview.getElementsByTagName('--'); //Get all dropdown lists contained in GridView1.
for (var i = 0; i < dropdowns.length; i++) {
if (dropdowns.item(i).value == '--') //If dropdown has no selected value
{
flag = false;
break; //break the loop as there is no need to check further.
}
}
if (!flag) {
alert('Please select value in each dropdown');
}
return flag;
}
</script>
here is my drop-down in the aspx:
<ItemTemplate>
<asp:Label ID="lblAns" runat="server" Text='<%# Eval("DDL_ANS")%>' Visible="false"></asp:Label>
<asp:DropDownList ID="ddl_Answer" runat="server" AutoPostBack="false">
</asp:DropDownList>
</ItemTemplate>
here is the code behind for the dropdown
ddl_Answer.DataSource = cmd1.ExecuteReader();
ddl_Answer.DataTextField = "DD_ANSWER";
ddl_Answer.DataValueField = "DD_ANSWER";
ddl_Answer.DataBind();
ddl_Answer.Items.Insert(0, new ListItem("--"));
How are you trying to select the dropdown using javascript. You probably want this
dropdowns = gridview.getElementsByTagName('select');

How to check whether the check box inside Gridview Template is Selected or not with Javascript?

I have a gridview which contains one templatefield checkbox to select the data for each row. Here they can select the members from the grid.
<asp:GridView ID="dgMembers2" runat="server" AllowPaging="True" AllowSorting="True">
<HeaderTemplate>
<asp:CheckBox ID="chkBxHeader" onclick="javascript:HeaderClick(this);" runat="server"
Text="Select All" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Gridview>
So, when they select member and click on ADD then its inserting into the database but if they do not select any checkbox from the grid I cannot show any error message. Can anyone suggest please how I can check this with Javascript that whether they have checked at least one checkbox or not and then I want to show
Javascript Alert
I tried a lot but my field is template field so I do not know how to work with it.
Any suggestion will be appreciable.
Use below code to make Select All/UnSelect All
function HeaderClick(CheckBox, gdvClientId) {
var TargetBaseControl = document.getElementById(gdvClientId);
var TargetChildControl = 'chkOrder';
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 = CheckBox.checked;
}
Call the function from your headertemplate like this
HeaderClick(CheckBox, gdvClientId), gdvClientId is your Gridview ID
maybe you could try add this javascript function to the ADD button onClientClick attribute.
function tryThis() {
var rowscount = document.getElementById('<%=yourGridViewID.ClientID%>').rows.length;
var chkTest = 0;
for (var i = 0; i < rowscount-1; i++) {
var chkName = "yourGridViewID_yourCheckBoxID_" + i;
var chkChecked = document.getElementById(chkName).checked;
if (chkChecked == true) {
chkTest = 1;
break;
}
}
if (chkTest == 0) {
alert('Nothing Checked');
}
else {
alert('Something Checked');
}
}
Hope this helps.
References:
How do I get if a checkbox is checked or not?
ASP.NET GridView row count using Javascript
Add asp.net CustomValidator control, and set js function
HTML Markup:
<asp:CheckBox ID="CheckBox1" runat="server" cssClass="chkd" />
<asp:CustomValidator runat="server" ID="validcontrol" EnableClientScript="true"
ClientValidationFunction="validchkbox">required.</asp:CustomValidator>
JavaScript Function:
function validchkbox(sender, e)
{
e.IsValid = $(".chkd input:checkbox").is(':checked');
}
Code behind:
if (Page.IsValid)
{
// Logic Code here...
}
OR
Jquery makes life more easy for developer :
if ($('.chkd').is(':checked')){
alert("Heloo Welcome..");
}
else {
alert("Please select the checkbox.");
}
DEMO JS FIDDLE
Note: here chkd is your checkbox class name
let your gridview id is gv_test
than
function checkChecked() {
var count = 0;
$("#gv_test").find(":checkbox").each(function (i) {
if ($(this).is(":checked")) {
count++;
}
});
if (count == 0) {
alert('your error message');
}
}
hope this will work. Thank you.

Update ASP Label inside ASP Datalist

I have an ASP Datalist with a nested GridView.
I am trying to display an ASP label for each list item where the gridview has more than 6 rows and keep it hidden for those list items where the gridview has < 6 rows.
Here is the datalist:
<asp:DataList runat="server" id="listResponses" DataKeyField="QuestionID" OnItemDataBound="listResponses_ItemDataBound" Width="100%">
<ItemTemplate>
<div class="question_header">
<p><strong><asp:Label ID="lblOrder" runat="server" Text='<%# Container.ItemIndex + 1 %>'></asp:Label>. <%# DataBinder.Eval(Container.DataItem, "QuestionText") %></strong></p>
</div> <!-- end question_header -->
<asp:GridView runat="server" ID="gridResponses" DataKeyNames="AnswerID" AutoGenerateColumns="False" CssClass="responses" AlternatingRowStyle-BackColor="#f3f4f8">
<Columns>
<asp:BoundField DataField="AnswerTitle" HeaderText="Answer Title" HeaderStyle-ForeColor="#717171" ItemStyle-Width="250px"></asp:BoundField>
<asp:BoundField DataField="Responses" HeaderText="Response Count" HeaderStyle-ForeColor="#717171" HeaderStyle-Width="100px" />
<asp:TemplateField>
<ItemTemplate>
<div class="pbcontainer">
<div class="progressbar"></div>
<asp:HiddenField ID="hiddenValue" runat="server" Value='<%# Eval("Responses") %>' />
</div>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<a><asp:Label runat="server" ID="lblShowResponses" Visible="false"></asp:Label></a>
</ItemTemplate>
</asp:DataList>
The label I am trying to update is lblShowResponses.
The method to populate the datalist:
// populate datalist.
DT = GetData.GetQuestionNameDataList(qid);
listResponses.DataSource = DT;
listResponses.DataBind();
And the gridview is populated as follows:
protected void listResponses_ItemDataBound(object sender, DataListItemEventArgs e)
{
GridView gridResponses = (GridView)e.Item.FindControl("gridResponses");
BindGrid(gridResponses, (int)listResponses.DataKeys[e.Item.ItemIndex], DT.Rows[e.Item.ItemIndex][2].ToString());
}
// Get the question ID from the datalist and parse the parameters to BindGrid
protected void listResponses_ItemDataBound(object sender, DataListItemEventArgs e)
{
GridView gridResponses = (GridView)e.Item.FindControl("gridResponses");
BindGrid(gridResponses, (int)listResponses.DataKeys[e.Item.ItemIndex], DT.Rows[e.Item.ItemIndex][2].ToString());
}
private void BindGrid(GridView GridView, int questionId, string questionType)
{
// get the answerID and title for the current question.
DataTable answersDataTable = new DataTable();
answersDataTable = GetData.GetAnswerResponses(questionId);
DataTable tempResponses = new DataTable();
// checkbox question type - loop through each answer and obtain the number of responses.
for (int answer = 0; answer < answersDataTable.Rows.Count; answer++)
{
// populate tempaory datatable and replace DT with the response count.
string answerID = answersDataTable.Rows[answer][0].ToString();
tempResponses = GetData.getIndividualQuestionResponses(questionId, answerID);
answersDataTable.Rows[answer][2] = tempResponses.Rows[0][0];
}
if (GridView.Rows.Count > 6)
{
for (int x = 6; x < GridView.Rows.Count; x++)
{
GridView.Rows[x].Visible = false;
}
// I want to populate the label here!!!!!!
}
}
How can I update/populate the label lblShowResponses when the gridview contains more than 6 rows?
Not sure if this would help you, pass the DataListItemEventArgs param "e" to the BindGrid method and in the location you want to populate the label and use
(e.Item.FindControl("lblShowResponses") as Label).Text = "Test";
(e.Item.FindControl("lblShowResponses") as Label).Visible = true;

check/uncheck all checkbox of datalist on button click which is outside of datalist

I hava a datalist in side that I have checkbox
<asp:DataList ID="dlst1" runat="server" RepeatDirection="Horizontal" OnItemDataBound="dlst1_ItemDataBound" CaptionAlign="Left">
<ItemTemplate>
<asp:ImageButton ID="btnImage" runat="server" />
<asp:Label ID="lbl" runat="server"/>
<asp:CheckBox ID="Chkbox" runat="server" TextAlign="Right" />
</ItemTemplate>
</asp:DataList>
I have 2 button
I want to check all the check box when user click on Check All btn, and Uncheck All checkbox when user click on Uncheck All btn, I don't want any post back, how to do it in client side.
I am trying
function CheckOrUncheckAll(isChecked) {
var dataList = document.getElementById('<%= DataList.ClientID %>');
for (var index = 0; index < dataList.rows.length; index++) {
for (var cIndex = 0; cIndex < dataList.rows[index].cells.length; cIndex++) {
dataList.rows[index].cells[cIndex].childNodes[3].checked = isChecked;
}
}
return false;
}
<asp:Button ID="btnCheckAll" runat="server" Text="Check All" OnClientClick="return CheckOrUncheckAll(true)" />
<asp:Button ID="btnUnCheckAll" runat="server" Text="Uncheck All" OnClientClick="return CheckOrUncheckAll(false)" />
its working fine but I don't want to use childNodes[3], because in future in in datalist something got added then I need to change the index.. any jquery to change this function
please try below
function CheckUnCheckAll(checkoruncheck)
{
var list = document.getElementById("<%=dlst1.ClientID%>") ;
var chklist = list.getElementsByTagName("input");
for (var i=0;i<chklist.length;i++)
{
if (chklist[i].type=="checkbox" )
{
chklist[i].checked = checkoruncheck;
}
}
}
call this as
CheckUnCheckAll(true);
or
CheckUnCheckAll(false);
I think, you must use jQuery.
To check:
$("#<%=btnCheckAll.ClientID %>").click(function() {
$("#<%= dlst1.ClientID %> input:checkbox").attr("checked", "checked");
});
To uncheck:
$("#<%=btnUnCheckAll.ClientID %>").click(function() {
$("#<%= dlst1.ClientID %> input:checkbox").removeAttr("checked");
});

Acces label in footertemplate of gridview in javascript

I have a label in a footertemplate of a gridviewcolumn. I want to put a calculated value (total of the rowvalues) in this label in javascript. I can access all the textboxes in my Itemtemplates, but I don't know how to find my label in my foortertemplates.
.aspx: column in gridview
<asp:TemplateField HeaderText="Prijs excl. BTW">
<ItemTemplate>
<asp:TextBox ID="txtBTWTarief" Width="60px" runat="server" Text='<%# Eval("exclBTW") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotexclBTW" runat="server" Text="0" Width="60px"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
.aspx.cs: eventhandlers attached to my textboxes and ddl
protected void gridviewDiversen_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string evtHandler;
int rowIndex = Convert.ToInt32(e.Row.DataItemIndex) + 1;
evtHandler = "updateValue(" + gridviewDiversen.ClientID + "," + rowIndex + ")";
((TextBox)e.Row.FindControl("txtBTWTarief")).Attributes.Add("onblur", evtHandler);
((TextBox)e.Row.FindControl("txtKorting")).Attributes.Add("onblur", evtHandler);
((DropDownList)e.Row.FindControl("ddlBTW")).Attributes.Add("onchange", evtHandler);
}
}
javascript: eventhandlers in action
function updateValue(theGrid, rowIdx)
{
var ddl, t1, t2, l1, l2, l3, l4, k1;
ddl = document.getElementById(theGrid.rows[rowIdx].cells[2].children[0].id);
t1 = document.getElementById(theGrid.rows[rowIdx].cells[3].children[0].id);
//calculations...
}
In this script I find my textboxes in the Itemtemplate, but I don't know how to find my labels in the footer template. Anyone an idea? Thx
If you do calculations in JS and need to find the label using client side you can use jQuery:
$('.yourLabelClass').html('Updated results');
or just JS:
var labels = document.getElementsByTagName("span");
for (var i=0; i < labels[i]; i++) {
if (labels[i].className && labels[i].className == 'yourLabelClass')
labels[i].innerHTML = 'Updated results';
}

Categories

Resources