Using Asp.Net Java Script to dynamically change the color of Gridview rows based on the logic implemented in the code

I've been trying to change the color of each row in gridview1 based on a loop using JavaScript. However, whenever I click the Upload button, the loop runs but the color doesn't change as expected.

It's frustrating because I can't figure out what I'm missing.

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
    With GridView1
        For i = 1 To .Rows.Count - 1
            btnUpload.Attributes.Add("onClick", "ChangeColor('" + "GridView1','" + (i).ToString() + "')")
        Next
    End With
End Sub



<script type="text/javascript">
        function ChangeColor(GridViewId, SelectedRowId) {
            var GridViewControl = document.getElementById(GridViewId);
            if (GridViewControl != null) {
                var GridViewRows = GridViewControl.rows;
                if (GridViewRows != null)
                {
                    var SelectedRow = GridViewRows[SelectedRowId];
                    //Remove Selected Row color if any
                    for (var i = 1; i < GridViewRows.length; i++) {
                        var row = GridViewRows[i];
                        if (row == SelectedRow) {
                            //Apply Yellow color to selected Row
                            row.style.backgroundColor = "#ffffda";
                        }
                        else {
                            //Apply White color to rest of rows
                            row.style.backgroundColor = "#ffffff";
                        }
                }

                }
            }

        }
</script>

Answer №1

If you're looking to avoid attaching an OnClick in the OnRowDataBound event, you can utilize this code snippet below. This method assumes that the upload button is defined as a Button rather than a LinkButton; however, it can be easily adjusted as needed.

<script type="text/javascript>
    $(document).ready(function () {
        $('#<%= GridView1.ClientID %> input[type="submit"]').click(function () {
            $(this).closest('tr').css('background-color', '#00ff00');
        });
    });
</script>

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 is the best way to retrieve the true CSS property value of an HTML element node?

My understanding of the getComputedStyles() method is that it returns an object enabling access to the actual CSS property values of an HTML element node. I decided to test this concept by creating a simple example with a paragraph that contains a span: ...

Is there a way to navigate to the home page using a PNG icon without refreshing the page when clicked on, while also utilizing NavLink with a route of '/'?

Here's the code I'm working with: <div key="1" className="menu-item"> <NavLink to="/"> <span className="icon-home3" />&nbsp; Home </NavLink> </div> The Home button functions ...

Client-side resizing an image before sending it to PHP for uploading

Greetings! Currently, I am utilizing a JavaScript library from this source to resize images on the client-side. The image resizing process works successfully with the following code: document.getElementById('foto_select').onchange = function( ...

Modifications in dll files when migrating a web application from Visual Studio 2008 to 2012

Should I use an ASP.NET web application that was created using Visual Studio versions 2008 to 2013 while keeping the .NET framework at version 3.5? I am worried about potential changes to the .csproj and .sln files when opening the project in Visual Studi ...

Experience the power of CanJS Observable data objects with the added feature of

When working with canJS Observable, I encountered an issue where I cannot use dots in object keys because canJS interprets them as nesting. For example, if I try to create a new observable like this: var obs = new can.Observe( { "div.test-class": { "color ...

Angular: Transforming a JSON Response to a JSONP Response

I'm currently using the openweathermap API to fetch JSON data, but I'm interested in utilizing JSONP data instead. How can I achieve this in my Angular service? app.factory('forecast', ['$http', function($http) { t ...

Challenges in communication between jQuery/JavaScript and PHP

Currently, I am in the process of setting up a basic client/server communication using jQuery/JavaScript and PHP. Everything is functioning smoothly until a period '.' is present in the data. I have experimented with the following scenarios: as ...

Is it possible to create two sticky headers with varying heights?

Looking to develop a website featuring two sticky elements at the top of the page - a sticky header and a sticky toolbar. Utilizing Bootstrap's Affix for the toolbar and sticky.js for the header. Encountering an issue where setting {topSpacing:0} cau ...

What is the best way to activate an Asp.net application when there is a change in the database?

On a webpage built with ASP and C#, I have created a button that, when clicked, extracts data from a database and sends a request to a web service based on that data. The result is then displayed on another page. Additionally, there is hardware in place th ...

What is the process for calculating and determining the exact area the div should be released?

I am currently developing a drag-and-drop application using only Javascript. I have successfully implemented the dragging functionality, allowing elements to be moved randomly within the page. However, I now face the challenge of creating a drop zone with ...

Unexpected log4net file naming behavior

I have a web application built with ASP.Net that utilizes log4net for logging. I prefer to create a daily log file, so my configuration appears as follows: <appender name="RollingFile" type="log4net.Appender.RollingFileAppender"> <file type="lo ...

Showing an array in angular.js

When sending data to a PHP file, the file processes it and performs an SQL search, returning a list of names in a for each statement. For example: Ryan, Jack, Billy, Sarah. However, when echoing the response in Angular, all the names are joined together l ...

Run JavaScript code to retrieve the console log using Selenium WebDriver or WatiN

(Apologies for the detailed explanation) I am looking to ensure a page loads entirely before proceeding, but it seems browsers have varied responses when attempting to use readyState or onLoad. In the application I am currently developing, a specific l ...

Issues detected with the functionality of Angular HttpInterceptor in conjunction with forkJoin

I have a Service that retrieves a token using Observable and an HttpInterceptor to inject the token into every http request. It works seamlessly with a single request, but when using forkJoin, no response is received. Here is the code for the interceptor: ...

Preventing file uploads from users on an ASP.NET 4.0 Application is necessary

I am currently facing difficulties setting up a section on a .net 4.0 platform that allows users to upload files. Despite my attempts, I have not been successful in configuring the necessary permissions for the directory intended to store these files. Even ...

A useful guide on how to fetch information in the front end from res.send and dynamically generate a page for every item in the database

I have a variable named data which holds an Array where each item has a unique ID. app.get('/products/:id', function (req, res) { res.send(data.map(data => "" + data.id + "")) //retrieves data of the element in the Array ...

AngularJS - Use promise instead of returning a data object

I am currently working on a project using AngularJS. Within my service.js file, I am attempting to retrieve some values. However, instead of receiving the actual data, I am getting back a promise object with some $$variables along with the desired data. ...

Organize divs based on their attributes

Using inspiration from this SO post, my goal is to group divs based on their "message-id" attribute. The idea is to wrap all divs with the same "message-id" in a div with the class name "group". <div class="message" message-id="1"> ...

Retrieve the chosen checkbox items with a single button click

Is there a way to retrieve the ID of a checked checkbox item in a list when a button is clicked, and then store those items in a variable or array for future use? Sample HTML: <input id="btnCheck" type="button" value="Next" ng-click="addSelected()" /& ...

Angular enables flashcards to smoothly transition in and out through sliding

Context I'm currently developing a flashcard web application using Angular, and I'm facing challenges with implementing smooth sliding transitions for the flashcards. The app allows users to create flashcards through input fields which are then ...