Utilizing jQuery to dynamically update background colors within an ASP repeater based on the selected value of a dropdown list

On my asp.net web page, I have a repeater that displays a table with various fields in each row. I am trying to make it so that when the value of a dropdown within a repeater row changes, the entire row is highlighted in color. While I have achieved this server-side, I am looking to implement this functionality on the client-side instead.

Below is the code snippet:

HTML

<table id="InvoerUrenTable" class="InvoerUrenLeftMargin100">
<asp:Repeater ID="urenRepeater" runat="server">
    <ItemTemplate>
        <tr runat="server" ID="itemTemplateRow">
            ...
            ...
            ...
            <td>
                <asp:DropDownList runat="server" ID="projectDropDown"></asp:DropDownList>
            </td>
            ...
            ...
            ...
            ...
        </tr>
    </ItemTemplate>
</asp:Repeater>
</table>
<script type="text/javascript">
      $(document).ready(function () {
          $('#projectDropDown').change(function () {
              var index = $(this).parent().children().index($(this));
              $('#urenRepeater tr:nth-child(' + index + ')').addClass("highlight")    
          });
      });
</script>

CSS

.highlight {
background-color: #E52718;
}

The script presented above does not seem to be working as expected. Can someone point out what might be going wrong?

UPDATE 06/07/2020

I discovered that I was targeting the incorrect row ID for changing the class attribute.

<script type="text/javascript">
      $(document).ready(function () {
          $('.projDropDown').change(function () {
              var index = $(this).parent().children().index($(this));
              $('#body_urenRepeater_itemTemplateRow_' + index).addClass("highlight")    
          });
      });
</script>

However, I am now facing an issue where the index is incorrect, and it highlights the first row every time I change the value in one of the dropdowns. Any suggestions on how to fix this?

Answer №1

As the dropdown is located within a repeater, it may be duplicated multiple times on the final page. This could result in either unique IDs being assigned by asp.net to ensure uniqueness in the browser-rendered HTML, or multiple dropdowns with the same ID, which is not valid. In both scenarios, there will be challenges for jQuery to properly target the correct dropdown.

For a solution, I recommend using a CSS class as a selector instead. This way, the class won't be affected by the rendering engine of asp.net, and you can also apply one event handler to multiple elements.

For example:

<asp:DropDownList runat="server" ID="projectDropDown" CssClass="projDropDown" ></asp:DropDownList>

and

$('.projDropDown').change(function () {

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

Oops! An error occurred when attempting to log in with an unidentified authentication method called "local"

After following a tutorial to build my project, I encountered an issue with the login functionality. While the signup process works fine, attempting to log in a registered user using postman results in the error: Error: Unknown authentication strategy "loc ...

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

What possible reason could there be for the empty space on the left side?

<ul style="background: blue; list-style: none; width: 40px; height: 40px; color: white"> <li style="float: left; width: 20px; background: red">a</li> <li style="float: left; width: 20px; background: green; height: 40px">b</li ...

Using require to access an Immediately Invoked Function Expression variable from another file in Node.js

File 1 - Monitor.js var MONITOR = (function () { // Code for Monitoring return { doThing: function() { doThing(); } }; })(); File 2 - Test.js var monitor = require('../public/js/monitor.js'); I am trying to access the doThing() funct ...

JavaScript utilizing an API to retrieve specific data values

Below is some API Data that I have: [ { "symbol": "AAPL", "name": "Apple Inc.", "price": 144.98, "changesPercentage": -1.22, "change": -1.79, ...

Assign variable a new value when link is clicked

On my ASP.NET webpage, I have a listview that showcases "cottage" records retrieved from an Access database. Each cottage's name is displayed as a clickable link which redirects to another page: <li style="">Name: <asp:Hyperlink ID="Cot ...

"Sharing JSON data with the client side using Express and Node.js: A step-by-step guide

I am currently working on an application that requires sending form data through XMLHttpRequest. The process involves validating the form data on the server side and then providing feedback to the client based on the validation result. In this project, I a ...

When using a function linked to an API request, an uncaught TypeError is thrown: Unable to access the 'includes' property of an undefined value

Utilizing the movie DB API (), I am displaying the results of my call on my page using Vue. The API supplies all the necessary data for me to achieve my objective, as demonstrated in this image https://i.stack.imgur.com/vP4I2.jpg Beneath each show's ...

Choosing options from Bootstrap dropdown using Protractor

I am working with a Bootstrap single-button dropdown and I need to programmatically click on one of the options in the dropdown using Protractor. How can I achieve this? <div class="btn-group" ng-if="!persist.edit" dropdown> ...

npm not only loads the packages specified in my package.json file

Currently, I am working on a small project utilizing npm, bower, and grunt. Upon executing "npm install" on my personal computer, it seems to be loading an excessive amount of peculiar items (refer to attached screenshot). However, when performing the same ...

The type 'Observable<void | AuthError>' cannot be assigned to 'Observable<Action>'

I am encountering an error that reads: error TS2322: Type 'Observable<void | AuthError>' is not assignable to type 'Observable<Action>'. Type 'void | AuthError' is not assignable to type 'Action'. Type &a ...

Improved efficiency in CSS for left transition animations

Here is the current code I am using: .s2 { top: 150px; left: 20px; position: absolute; transition: left 300ms linear; } I am currently updating the left position dynamically using JavaScript based on scroll events. However, I have noticed that th ...

When using React, the event.target method may unexpectedly return the innerText of a previously clicked element instead of the intended element that was

I have implemented a drop-down menu that triggers an event handler to return the selected option when it is clicked. Upon clicking on an option, I retrieve the inner text of that option using the event. The code snippet looks like this: event.target.inner ...

Array filtering functions similarly to marketplace filtering tools

In order to make the filter function like a marketplace filter, I want to only see items related to the selected brand and status. For example: partners = [ 0:{ year: "2022" badge_status: "badge-success" sale_date: "01/07/2022&quo ...

Utilizing MDX Component Properties in NextJS

Currently, I am in the process of developing a layout system for my upcoming app inspired by Adam Wathan's approach and his tailwind website. While I have successfully implemented it for js files, I am facing issues trying to apply the same syntax to ...

Utilizing JSON data to generate an HTML webpage showcasing a collection of community districts through the power of JavaScript

As a beginner in javascript, I am working with a JSON file that contains an array of objects. Each object includes two properties: a borough and mappings. Mappings have two sub-properties called macro and neighborhoods. The macro represents a larger neighb ...

The concept of CSS Parent Elements refers to the relationship

Is it possible to dynamically apply CSS style based on the parent property of a div element using JavaScript? Here is an example: <div clas="parent"> <div class="child"> <div class="x"></div> </div> </d ...

Is concealing content using Javascript or jQuery worth exploring?

While I have been hiding content using display:none; in css, there are concerns that Google may not like this approach. However, due to the needs of jQuery animations, it has been necessary for me. Recently, I have come across a new method for hiding conte ...

Is the onmouseover / onmouseout transition failing to function properly?

Is there a way to make the ease-in-out effect work without modifying the HTML code? http://jsfiddle.net/68ojLg6p/ <img class="transition-img" onmouseover="this.src='http://1.bp.blogspot.com/-ISjKMLTnaTQ/Ty-USX-J1uI/AAAAAAAAC_0/YB6MUMflRmg/s400/fe ...

The UI does not display the html code (specifically svg) added through jquery appending

I am working with the following HTML code: <svg> <g> <rect></rect> <text> abc </text> </g> <g> <rect></rect> <text> def </text> </g& ...