Locate the checkbox and textbox embedded within a gridview using JavaScript

I am trying to retrieve the value of a checkbox inside a grid view. When the checkbox is checked, I want the corresponding textbox in that row to be enabled, and if it is unchecked, the textbox should be cleared and disabled. I posted this question a few hours ago but have not yet received a satisfactory answer. My attempt so far:

//Code for my grid.

<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>

//Here's 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++) {
             if (GridView.rows[Row].cell[3].type == "checkbox")
                 (GridView.rows[Row].cell[3].type).checked = true;
         }
     }
 }
 </script>

Answer №1

This effective solution has been thoroughly tested and proven to succeed by utilizing solely JavaScript (without the need for jQuery).

1. C# Part (Within Page_Load Method)

To implement this functionality, a minor tweak is required in the Page_Load:

foreach(GridViewRow row in YourGridViewControlID.Rows)
{
    if (row.RowType == DataControlRowType.DataRow )
    {
      ((CheckBox) row.FindControl("YourCheckBoxID")).Attributes.Add("onchange", "javascript:TextboxAutoEnableAndDisable(" + (row.RowIndex ) + ");");
    }
}

This enhancement ensures that the JavaScript function is invoked on the OnChange event of each individual CheckBox within the GridView. The ability to pass the Row Index as a parameter distinguishes this approach from traditional HTML methods.

2. Key Considerations for the HTML Component

It is crucial to maintain static IDs for both the Checkbox and Textbox controls, as well as the GridView Control using the attribute ClientIDMode="Static" as illustrated below:

<asp:CheckBox ID="YourCheckBoxID" runat="server" ClientIDMode="Static"/>
<asp:TextBox ID="YourTextBoxID" TextMode="SingleLine" runat="server" ClientIDMode="Static" />

For the GridView control:

<asp:GridView ID="YourGridViewControlID" ...... ClientIDMode="Static" runat="server">

3. Javascript Component

In your JavaScript file/code:

function TextboxAutoEnableAndDisable(Row) {
  // Obtain the current active row within the GridView.
  var GridView = document.getElementById('YourGridViewControlID');
  var currentGridViewRow = GridView.rows[Row + 1];

  // Identify the relevant controls.
  var rowTextBox = currentGridViewRow.cells[2].getElementsByTagName("input")[0];
  var rowCheckbox = currentGridViewRow.cells[0].getElementsByTagName("input")[0];

  // Handle scenario when checkbox is unchecked.
  if( !rowCheckbox.checked) {
    // Empty textbox and disable it
    rowTextBox.value = "";
    rowTextBox.disabled = true;
    return;
  }

  // Enable the textbox if checkbox is checked.
  rowTextBox.disabled = false;
}

4. Additional Notes for Implementation

  • Note that in the JavaScript code, at the line:
    var currentGridViewRow = GridView.rows[Row + 1];

    the [Row + 1] is critical for proper functioning and should remain unchanged.
  • Lastly:

The following lines require attention:

var rowTextBox = currentGridViewRow.cells[2].getElementsByTagName("input")[0];
var rowCheckbox = currentGridViewRow.cells[0].getElementsByTagName("input")[0];

The values within .cells[2] and .cells[0] may vary based on your setup, necessitating correct adjustment within the brackets.
Typically, these numbers correspond to the column positions within your GridView, starting from 0.

For instance, if the CheckBox resides in the first column of the GridView, use .cells[0].
Similarly, if the TextBox occupies the second column, employ .cells[1] (in my example, the TextBox was situated in the third column, hence .cells[2] was utilized).

Answer №2

Opt for using the onclick JavaScript over the OncheckedChanged event, as it is a server-side event specific to CheckBox.

<asp:CheckBox ID="CheckBox2" runat="server" onclick="Javascript:JSfunctionName();" />

Update:

var GridView = document.getElementById('<%=DeptGrid.ClientID %>')

Update: As per your request in the 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
    }
 }

Answer №3

Upon further investigation, I discovered that using the statement if (GridView.rows[Row].cell[2].type == "checkbox") led to an error where GridView.rows[Row].cell[2].type is undefined. My current code implementation is shown below:

    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) {
                // performing certain actions here
                alert('function executed for row ' + row);
            }                                  
        }

Answer №4

The grid can be defined in the following manner:

 <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>

For the associated Javascript function:

<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 function is triggered by the onblur event of the textbox and accepts the textbox id as a parameter.

Inside the function, we retrieve the value of the textbox using the provided parameter:

      var cntNbr = $("#" + obj.id).val();

We then loop through each "txtPeriod" control within the grid and assign the current textbox value to them:

 $("#<%=GridView1.ClientID %> input[name*='txtPeriod']").each(function (index) {

 });

In this loop, we check if the value is not null or NaN before assigning it to other "txtPeriod" textboxes:

               if ($.trim($(this).val()) != "")
                 if (!isNaN($(this).val())) {
                     $(this).val(cntNbr);
                 }

Answer №5

Greetings! Here is a simple solution for you.

Imagine your grid has the following structure:

<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>

Additionally, here is the JavaScript code to locate controls within your grid:

   <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>

Answer №6

Locate and access controls within a grid using Java Script:

for (var r = 1; r < grid.rows.length; ++r) {

    var indexValue = 0; //adjust for different browsers like IE8
    var txtPeriod= grid.rows[r].cells[2].childNodes[indexValue];
    if (typeof(txtPeriod.value) == "undefined")//check for IE9                      
        indexValue = 1;
     var txtPeriod= grid.rows[r].cells[2].childNodes[indexValue];
     alert(txtPeriod.value);
}

Answer №7

let elements = document.getElementById('<%=grdResults.ClientID%>').querySelectorAll("input");
let count = 0;
for (let j = 0; j < elements.length; j++) {
     if(elements[j].type == "checkbox" && elements[j].checked) {
          count++;
     }
}
alert("Number of checked items: " + count);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Interaction should always be triggered by the user" - a guideline to keep in mind when using SaveFileDialog in Silverlight 3

Currently, I am developing a Silverlight 3 application using C# and I have a requirement where I want to allow users to download an image from the Silverlight app. I am utilizing the SaveFileDialog to manage the file download process. The sequence of actio ...

Angular Material Clock Picker for 24-Hour Time Selection

Struggling to find a time picker component that supports the 24-hour format for my Angular 14 and Material UI application. Can anyone help? ...

Setting the default value for drop-down menus in jqGrid form editing

I have a data object with 3 attributes: ID Abbreviation Description In my jqGrid setup, I've configured the grid to display the Abbreviation. During editing (using the Form Edit feature), I populate the dropdown list with ID/Description pairs usin ...

What is the best way to share an array that is declared in one JavaScript file with another JavaScript file?

I wrote this code snippet: var json = result; AJS.log("JSON Data Print") AJS.log(json) var treeData = []; json_arr.push(json); /*for(var x in json){ json_arr.push(json[x]); }*/ AJS.log("Copying JSON Data into an array") AJS.log(treeData) Is there a ...

Error message when using Vue Global Filter: Value undefined is not defined

Trying to format currency, I initially attempted to use a global filter in Vue: Vue.filter('formatMoney', (val) => { if (!value) return '' val = val.toString() return val.replace(/\B(?=(\d{3})+(?!\d))/g, ",") ...

Implement a function that runs upon Page Load using Javascript

Here is some Javascript code that loads a map with different regions. When you hover or click on a country, additional information about that country is displayed on the right side of the map. I would like to have a random country already displaying infor ...

"Fixing the issue of ASP.Net MVC DropList binding the value to an incorrect

I have a model that consists of a setID string and a list of strings for woID. The set represents a collection of work orders. I am having trouble binding the selected value of the dropdown to woId. When I check the console, only setID is being displayed. ...

XPages component retrieval function is malfunctioning

Utilizing an XPage with JQuery dialog and client-side validation adds efficiency to the user input process. However, there seems to be a disconnect between the client-side validation and server-side properties. Although the client-side validation functions ...

Display requested tab feature using jQuery upon page load

I am new to jquery and have been using this code for creating tabs: <script type="text/javascript" charset="utf-8> $(function () { var tabContainers = $('div.tabs > div'); tabContainers.hide().filter(':first&apo ...

Adding clickable text to dynamically generated tables using JavaScript

I've created a dynamic table populated with data from a JSON response. This table consists of 3 columns - one for Serial Number, another for Name, and the third column is meant to have two clickable text links labeled as Edit and Delete. When clickin ...

Do not allow negative values to be displayed in the text box

Plunker I need to restrict negative values from being entered into a text field. If the user tries to input a negative value, I want the text box to remain unchanged. Although I have a directive that prevents negative values from being entered, it seems ...

I'm finding it difficult to grasp the purpose of $inject within controllers

I'm feeling completely lost when it comes to understanding inject in Angular. I can't seem to grasp where it should be utilized and its purpose. Is it specifically tied to factory methods, as outlined here? myController.$inject = ['$scope&a ...

The server is failing to provide the requested data in JSON format

I am struggling with making a simple API call using Node.js as the backend and React in the frontend. My Node.js file is not returning data in JSON format, and I'm unsure of the reason behind this issue. I need assistance with two main things: Why is ...

Angular directive ng-clickIs the directive in angular known as

I am struggling to understand why my ng-click function in my directive is not triggering the fooControls clickTest. Why isn't clickTest logging to the console? Is there a more efficient way to accomplish this? Custom Directive app.directive('fo ...

Using ES6 Babel with multiple package.json files

For a large project, I am looking to break it down into multiple package.json files. This way, the dependencies for each part can be clearly defined and exported as separate entities. However, my goal is to compile all of these packages using webpack and ...

Creating dependent dropdown lists is a useful way to streamline data entry and ensure accuracy in your

I am looking to create a series of 4 connected dropdown lists, structured like this: District: <select id="district"> <option>Select a District</option> <option value="district1">dstrict1</optio ...

I am interested in deleting an element from Firebase using JavaScript

I'm struggling to grasp the concept of deleting an item from my Firebase database. I have successfully created a function (saveEmployee) to add items, but removing them is where I hit a roadblock. HTML <tbody ng-repeat="employee in employees"> ...

A guide on encrypting the data of a file that is uploaded in Meteor.js

As a newcomer to Meteor and coding in general, I have completed tutorial projects and examples and now feel ready to start my own project. I want users to be able to select a file from their computer using an input field, read the contents of the file, and ...

Utilizing ASP.NET Impersonation for Secure SQL Server Trusted Connection Requests

While developing an ASP.NET page, our team has implemented code to impersonate the requesting user. The following code snippet is used to initiate the impersonation: Dim impersonationContext As System.Security.Principal.WindowsImpersonationContext Dim cur ...

Attempting to create a redirection landing page

I have a process where I create a new user and save it in my database with the following code snippet: const newUser = new User({ username: userId, password: pass, nameOfUser: user_name, emailOfUser: user_email ); newUser.save(); res.redir ...