Is there a way to trigger a JavaScript function upon checking a checkbox?

Is there a way to trigger a Javascript function when a checkbox within a gridview is checked?

protected void ChangeStatusSevenDays_Click(object sender, EventArgs e)
{
    for (int i = 0; i < grdImoveis2.Rows.Count; i++)
    {
        GridViewRow RowViewSevenDaysExpire = (GridViewRow)grdImoveis2.Rows[i];
        CheckBox chk = (CheckBox)grdImoveis2.Rows[i].FindControl("chkExpiraSeteDias");
        if (chk != null)
        {
            String code;
            if (chk.Checked)
            {
                code = (String)grdImoveis2.Rows[i].Cells[0].Text;                        
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Register", "ChangeStatus(code);", false);
            }
        }
    }
}



<asp:GridView ID="grdImoveis2" CssClass="StyleGrid" Width="100%" runat="server" AutoGenerateColumns="false" DataSourceID="ds" BorderWidth="0" GridLines="None">
    <AlternatingRowStyle BackColor="White" CssClass="AlternateRowStyleGrid"  HorizontalAlign="Center"/>
        <RowStyle CssClass="RowStyleGrid" HorizontalAlign="Center" />
        <HeaderStyle BackColor="#e2dcd2" CssClass="thGrid" Height="20" />
    <Columns>
        <asp:BoundField HeaderText="Code" DataField="Imovel_Id" />
        <asp:BoundField HeaderText="To" DataField="TransacaoSigla" />
        <asp:BoundField HeaderText="Price" DataField="ValorImovel" DataFormatString="{0:c}" HtmlEncode="false" />
        <asp:TemplateField HeaderText="Address">
            <ItemTemplate>
                <%# Eval("Logradouro") %>, <%# Eval("Numero") %>
            </ItemTemplate>
        </asp:TemplateField>
        
        <asp:BoundField HeaderText="Date Added" DataField="DataHora"  DataFormatString="{0:dd/MM/yyyy}" HtmlEncode="false"/>
        <asp:BoundField HeaderText="Expiration Date" DataField="DataExpira"  DataFormatString="{0:dd/MM/yyyy}" HtmlEncode="false"/>
      
        <asp:TemplateField HeaderText="Action">
            <ItemTemplate>
                <asp:CheckBox ID="chkExpiraSeteDias" runat="server" onclick="alert('Foo')" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

I've noticed that the image with a href link to Javascript works fine, but not when using checkboxes. Any suggestions?

Answer №1

Make sure to add the onclick attribute to your Checkbox HTML element and specify the Javascript function you want to execute.

<input type="checkbox" onclick="myFunction()" />

Answer №2

Here is a helpful tip for you

$('input:checkbox[ID$="chkExpiraTresDias"]').change(function() {
  alert('Hello everyone!');
});

Answer №3

It seems like the best approach would be to iterate through the Gridview on button click and perform necessary actions. Here's a sample code snippet:

foreach (GridViewRow row in this.grdImoveis2.Rows) {
    if (row.RowType == DataControlRowType.DataRow) {

        CheckBox chk = row.Cells(0).FindControl("chkExpiraTresDias");
        if (chk != null) {
            Response.Write(chk.Checked); //Implement your logic based on whether it's checked or not
        }
    }
}

Wishing you success.

Hanlet

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

What steps are needed to set up my Express server so that it can render all my content, rather than just my HTML file?

I need help setting up a server for my project using Express. Here is the structure of my file directory: root-directory ├── public │ ├── css │ │ └── styles.css │ ├── images │ │ └── img1.png | | └ ...

Step-by-step guide on setting up a click counter that securely stores data in a text file, even after the

Can anyone help me make this link actually function as intended? Right now it only runs the JavaScript code, but I would like it to run the code and redirect to a webpage. Additionally, I need the data to be saved to a text file. Please provide assistanc ...

Receiving the most recent data in a protractor examination as a text string

My goal is to fetch an input value for a specific operation in protractor. I am attempting to make an ajax request using protractor and need to assign a unique value (referred to as groupCode) to a JSON object that will be sent to the server. Initially, I ...

The functionality of the JavaScript click function is limited to a single execution

In my dropdown menu, I have a submit function that triggers whenever any children of the dropdown are clicked. However, I now need to exclude a specific li element from this function because it requires inserting a tracking ID in a popup iFrame. The code ...

JavaScript has been used to modify a cell's URL in jqGrid

Currently, I am utilizing struts2-jqgrid along with JavaScript. After the jqgrid has finished loading, it retrieves <s:url var="updateurl" action="pagosActualizar"/>. Subsequently, in the HTML view source, jqgrid generates options_gridtable.cellurl = ...

What is the best way to extract and retrieve the most recent data from an XmlHttpRequest?

Currently, I am using a web service that returns an SseEmitter to program a loading bar. The method to receive it looks like this: static async synchronize(component: Vue) { let xhr = new XMLHttpRequest(); xhr.open('PATCH', 'myUrl.co ...

Tips for initializing and updating a string array using the useState hook in TypeScript:1. Begin by importing the useState hook from the

Currently, I am working on a React project that involves implementing a multi-select function for avatars. The goal is to allow users to select and deselect multiple avatars simultaneously. Here is what I have so far: export interface IStoreRecommendation ...

Tips for resolving import errors encountered after running npm start

I recently started using React and I am currently following a tutorial. Even though I have the exact same code as the tutorial, I'm encountering the following error. ./src/index.js Attempted import error: './components/App' does not have a ...

The system is currently unable to find the specified element

I am facing an issue trying to locate a button that is defined under a specific class using XPATH. The error message "Unable to locate element" keeps popping up. Here are the details of the class: <div class="aui-button-holder inputBtn" id="aui_3_4_0_1 ...

Tips for keeping a reading item in place while scrolling

To enhance the user experience, I would like to improve readability without affecting the scroll position. Question: Is there a way to fix the scrolling item at a specific position (item with the .active class)? I am looking to maintain a consistent read ...

The like button seems to be malfunctioning and I'm not sure what the issue is

I've added the ability for users to like my posts, but it's not working as intended. Here's the code snippet I used: models.py class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(blank=Tru ...

What is the process for retrieving the value of a text box using V-Model?

Link to the code snippet <td><input class="input" v-model="user.name" /></td> After accessing the provided link, I noticed a unique input textbox. Is there a way to extract specific text values like a,b,c from this te ...

Is there a way to retrieve bookmarks (TOC) from a PDF document using technologies such as NodeJS, ReactJS, or PHP?

I'm sure most people have noticed that when you open a PDF in the browser or Acrobat PDF reader, a bookmarks tab appears like the one shown here: https://i.stack.imgur.com/obFer.png If the PDF doesn't have any bookmarks, the list will be empty. ...

Tips for leveraging OOP to eliminate redundant code repetition

How can I avoid repeating code when displaying multiple quizzes on the same page? Currently, I have a JavaScript function that duplicates everything for each quiz, with only a few variables changing in the second function. The problem arises when I need t ...

Error in node.js framework due to memory allocation issue

Hello, I'm encountering an issue while running my JavaScript program. I keep getting a memory error. Can anyone help me identify the exact problem? <--- Last few GCs ---> [12908:0000015EB93DE800] 29162 ms: Mark-sweep 1396.7 (1425.2) -> 1 ...

What is the best method for populating a complex array of a list of array structure in C#

I'm having difficulty populating this structure: var arrlist = new List<int[]>()[length]; What I am aiming for is an array with a fixed length of lists. Each list should contain an unknown number of arrays with a length of 2. Attempting to ad ...

The socket io server connection triggers repeatedly

Currently, I am working on developing a simple game using next.js and node.js. However, when I test the game, I notice that there are multiple "connected" logs being displayed. Even though I have only one client (with just a single tab open in Chrome), the ...

Failed installation of Semantic-ui through npm encountered

Encountering an error while attempting to install semantic-ui through npm for a new project. Here are the version details: $ node -v v16.14.0 $ npm -v 8.10.0 $ npm i semantic-ui npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Transforming precise military time using Angular and Javascript filtering

There are a few times where I find myself liking 01:45 //and 15:00 I believe this time format is HH:MM in military time? While I have come across some advanced functions that can parse sentences and even include seconds like HH:MM:SS, I am looking for a ...