Using JavaScript in ASP.NET with C# to enable a checkbox on Full Gridview row selection

Upon clicking a gridview row, I am able to check a column of checkboxes. However, this functionality is limited to a specific column only, as clicking directly on the checkbox itself does not trigger the action.

For example, when clicking anywhere in this section, the checkbox works as expected and remains checked:

https://i.sstatic.net/GXMSz.jpg

But, if I click on this other part, the checkbox functionality ceases to work:

https://i.sstatic.net/tBFNJ.jpg

Below are the relevant code snippets:

$(document).ready(function () {
    $('body').on('click', 'tr.dataRow', function () {
        var checked = $(this).find('input[id*=chkBusinessSelected]').prop('checked');
        $(this).find('input[id*=chkBusinessSelected]').prop('checked', !checked);
    });
});

var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_endRequest(function () {
    $('body').on('click', 'tr.dataRow', function () {
        var checked = $(this).find('input[id*=chkBusinessSelected]').prop('checked');
        $(this).find('input[id*=chkBusinessSelected]').prop('checked', !checked);
    });
});

<asp:GridView ID="grdBusiness" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical" Width="420px"  ShowHeaderWhenEmpty="True" EmptyDataText="No records Found" OnRowDataBound="grdBusiness_RowDataBound" DataSourceID="SqlDataSource3"    >
    <AlternatingRowStyle BackColor="White" />
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:CheckBox ID="chkBusinessSelected" runat="server"  />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="Code" HeaderText="Code" SortExpression="Code" />
        <asp:BoundField DataField="Business Type" HeaderText="Business Type" SortExpression="Business Type" />
    </Columns>
    <FooterStyle BackColor="#CCCC99" />
    <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
    <RowStyle BackColor="#F7F7DE" />
    <SelectedRowStyle BackColor="#90FF90" Font-Bold="True" ForeColor="Black"  />
    <SortedAscendingCellStyle BackColor="#FBFBF2" />
    <SortedAscendingHeaderStyle BackColor="#848384" />
    <SortedDescendingCellStyle BackColor="#EAEAD3" />
    <SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>

 protected void grdBusiness_RowDataBound(object sender, GridViewRowEventArgs e)
 {
     if (e.Row.RowType == DataControlRowType.DataRow)
     {
         e.Row.CssClass = "dataRow";     
     }
 }

Answer №1

After making some modifications to @UsmanKhalid's response, I successfully implemented the following code:

$(function () {
        $("#<%=grdBusiness.ClientID %> td").click(function () {
            toggleRowSelection($(this).closest("tr"));
        });
    });

    function toggleRowSelection(row) {
        var firstInput = row[0].getElementsByTagName('input')[0];
        firstInput.checked = !firstInput.checked;
    }

Answer №2

Check out this snippet:

$(function () {
        $("[id*=GridView] td").click(function () {
            chooseRow($(this).closest("tr"));
        });
    });

function chooseRow(row)
{
    var firstInput = row.getElementsByTagName('input')[0];
    firstInput.checked = !firstInput.checked;
}

Answer №3

Here is a useful tip:

$('tr.dataRow').on('click', function(){

  var checkbox = $(this).find('input[type=checkbox]');
    checkbox.prop("checked", !checkbox.prop("checked"));

});

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

Tips for creating a cursor follower that mirrors the position and size of another div when hovering over it

I am trying to create a cursor element that follows the mouse X and Y position. When this cursor hovers over a text element in the menu, I want it to change in size and position. The size of the cursor should match the width and height of the text being h ...

Can curly braces be utilized in the style section of Vue.js?

Can I utilize curly braces in the style section of vue.js to set a value? For instance .container { background: url({{ image-url }}; color: {{ color-1 }} } ...

Synchronizing timers among different elements

Just a little context: I'm diving into the world of React and currently working on a small app using next.js (with a template from a tutorial I followed some time ago). Lately, I've encountered a challenge where I need to synchronize a timer betw ...

What could be causing the "undefined property read" error even though the data is clearly defined?

export async function getPrices() { const res = await fetch( "https://sandbox.iexapis.com/stable/crypto/BTCUSD/price?token=Tpk_1d3fd3aee0b64736880534d05a084290" ); const quote = await res.json(); return { props: { quote } }; } export de ...

Reactive form within a parent object for nested counting

I am looking to generate a nested form based on the following data: The current data available is as follows: mainObject = { adminname: 'Saqib', adminemail: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="40 ...

Generating JSON data from a dropdown menu element

I'm working on a web page that showcases information for students in my database. One key field is their birth country, currently stored as the full name of the country. My goal is to convert these full country names into two-character strings. For ex ...

Finding the Ideal Location for Controllers in an Express.js Project

I'm relatively new to software development and one concept that I find challenging is organizing the directory structure of various projects. As I prepare to embark on an Express project, I prefer keeping controller classes separate from route callbac ...

Struggling to update a document fetched through a Mongoose model and handled as a promise

Check out update #2 for more detailed information I am encountering difficulties while trying to make a simple update to a document that has been retrieved by querying a container through a Mongoose model. The query using find has two populations, but oth ...

Experience the seamless integration of Restful APIs with AngularJS and Querystring parameters

I am currently in the process of developing a web application that includes edit functionality. Currently, I have created a page with a list of records, each containing an ID. When I click on the edit button, it triggers the following: $state.go ...

Is it possible to generate unique identifiers for v-for keys using vue-uuid?

I'm attempting to utilize a random string (UUID v4) using vue-uuid for existing items and future additions to the list in my to-do list style application. However, I'm uncertain about the correct syntax to use. After installation, I included it ...

.NET Core customization for creating multiple-to-multiple connections using a setter

Dealing with three tables that have a many-to-many relationship can be quite daunting. This relationship involves two tables and a joining table to connect them. The code structure for this is as follows: public partial class Test1 { public Test1() ...

Troubleshoot: Error loading my custom C# .Net plug-ins into Windows Live Writer

As a newcomer to .Net, I've been experimenting with writing a plugin for Windows Live Writer to streamline my blogging process. I find it more convenient to publish blogs using this platform rather than the web editors, and I have some ideas for small ...

Is there a way to send a preexisting JSON object to an OPTION in jQuery or JavaScript?

What is the best way to pass a preexisting JSON as a data value in an HTML option tag? I am aware that I can manually pass individual variables like this: <option data-value='{"name":"rajiv","age":"40"}'>a</option> However, if I ha ...

Steps for iterating over the "users" list and retrieving the contents of each "name" element

I'm attempting to iterate over the "users" array and retrieve the value of each "name". Although the loop seems to be functioning correctly, the value of "name" is returning as "undefined" four times. JavaScript: for(var i = 0; i < customer.users ...

Vue form component triggers the submit event twice

In my current project, I am utilizing the most recent version of Vue 3 without any additional vendors. After experiencing a setback in which I invested several hours attempting to uncover why my form component was triggering the submit event twice, I am le ...

How to effectively trigger a function to load images in React

When my react app loads, I want the images to load immediately. This involves calling the function collectionChanged(e.target.value) on application start. Inside a .jsx file, there is a function named getHomePage() which contains 4 functions. Upon calling ...

The progress indicator fails to appear in the foreground view

I am having trouble with the ProgressIndicator (MTMProgressHub) as it does not appear when brought to the front. hud = new MTMBProgressHUD(View); View.BringSubviewToFront(hud); View.AddSubview(hud); hud.Show(true); Please refer to the ima ...

What could be causing my CSS navigation toggle button to malfunction?

My attempt at creating a toggle button for tablets and phones seems to be failing. Despite the javascript class being triggered when I click the toggle button, it is not functioning as expected... https://i.stack.imgur.com/j5BN8.png https://i.stack.imgur. ...

Is there a way to expand the clickable area of JQuery sliders?

Check out some of the jquery ui sliders here One issue I am facing is that when you click the slider bar, the tic jumps to that exact part. This can be problematic because the bar is quite thin, making it easy to miss when trying to click on it. I want to ...

Develop an Angular resolver that can be utilized across various scenarios

Im searching for a method to apply a single angular route resolve to all of my routes, each with different parameters: currently, my setup looks like this: { path: 'user/:any', component: UserprofileComponent, resolve ...