Using jQuery to alter the colors of a dynamically generated table based on its content

I am currently working with a div element that dynamically generates a table.

Although I can generate the table and use

on("click" or "mouseover", function)
to achieve certain results, I need the table to update as it loads.

In my initial attempts, I tried using each() but realized it doesn't work on dynamic content. After further research, I switched to using on().

My goal is to avoid having to click on each cell for the changes to take effect.

Here's the jQuery code snippet:

$(function () {
    $("#outputDiv2").on('click', "td", function () {
        if ($(this).text() == 'notconnect') {
            $(this).css('background-color', '#d5d5c3');
        } else if ($(this).text() == 'connected') {
            $(this).css('background-color', '#00e600');
        } else if ($(this).text() == 'disabled') {
            $(this).css('background-color', '#cc0000');
        } else if ($(this).text() == 'err-disable') {
            $(this).css('background-color', '#ff9900');
        }
    });
});

You can view an example HTML table and script on jsfiddle by clicking the link below:

https://jsfiddle.net/frams/daknayhn/3/

Answer №1

To easily differentiate between different types in a table, you can utilize CSS classes for each type. When dynamically creating table rows, simply assign the respective class for each row.

.connected
{
  background-color: #00e600
  
}

.err-disable
{
  background-color: #ff9900
  
}

.disabled
{
  background-color: #cc0000
  
}

.notconnect
{
  background-color: #d5d5c3
  
}
<div id="outputDiv2">
  <table border="1>
    <tbody id="tableD">
      <tr>
        <td nowrap=""><a href="#'">Port</a></td>
        <td nowrap="">Name</td>
        <td nowrap="">Status</td>
        <td nowrap="">Vlan</td>
        <td nowrap="">Duplex</td>
        <td nowrap="">Speed </td>
        <td nowrap="">Type
        </td>
      </tr>
      <tr>
        <td nowrap=""><a href="#'">Fa0/1</a></td>
        <td nowrap=""></td>
        <td nowrap="" class="connected" >connected</td>
        <td nowrap="">1</td>
        <td nowrap="">auto</td>
        <td nowrap="">10 </td>
        <td nowrap="">10/100BaseTX
        </td>
      </tr>
      <tr>
        <td nowrap=""><a href="#'">Fa0/2</a></td>
        <td nowrap=""></td>
        <td nowrap="" class="connected">connected</td>
        <td nowrap="">1</td>
        <td nowrap="">auto</td>
        <td nowrap="">10 </td>
        <td nowrap="">10/100BaseTX
        </td>
      </tr>
      <tr>
        <td nowrap=""><a href="#'">Fa0/3</a></td>
        <td nowrap=""></td>
        <td nowrap="" class="notconnect">notconnect</td>
        <td nowrap="">1</td>
        <td nowrap="">auto</td>
        <td nowrap=""> auto </td>
        <td nowrap="">10/100BaseTX
        </td>
      </tr>
      <tr>
        <td nowrap=""><a href="#'">Fa0/4</a></td>
        <td nowrap=""></td>
        <td nowrap="" class="notconnect">notconnect</td>
        <td nowrap="">1</td>
        <td nowrap="">auto</td>
        <td nowrap=""> auto </td>
        <td nowrap="">10/100BaseTX
        </td>
      </tr>
      <tr>
        <td nowrap=""><a href="#'">Fa0/4</a></td>
        <td nowrap=""></td>
        <td nowrap="" class="err-disable">err-disable</td>
        <td nowrap="">1</td>
        <td nowrap="">auto</td>
        <td nowrap=""> auto </td>
        <td nowrap="">10/100BaseTX
        </td>
      </tr>
      <tr>
        <td nowrap=""><a href="#'">Fa0/4</a></td>
        <td nowrap=""></td>
        <td nowrap="" class="disabled">disabled</td>
        <td nowrap="">1</td>
        <td nowrap="">auto</td>
        <td nowrap=""> auto </td>
        <td nowrap="">10/100BaseTX
        </td>
      </tr>
    </tbody>
  </table>
</div>

Answer №2

Feel free to give this code a try!

$(function () {
    $("#outputDiv2").on('click', "td", function () {
       $('.notconnect').css('background-color', '#d5d5c3');
       $('.connected').css('background-color', '#00e600');
       $('.disabled').css('background-color', '#cc0000');
       $('.err-disable').css('background-color', '#ff9900');
  });
});

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 position two divs side by side while maintaining their individual padding?

When I remove the padding as shown, the website functions correctly with two div columns next to each other. However, upon adding padding, the #right div shifts downwards. How can I ensure it works as intended with padding included? HTML: Two divs direct ...

Unable to navigate to the frame within the Salesforce Lightning interface

Attached below is the screenshot and code that I have used: driver.switchTo().frame(driver.findElement(By.xpath("//iframe[contains(@title,'Deploy Data Set')]"))); <div class="slds-template_iframe slds-card" force-aloha-page_aloha-page=""> ...

Problem with organizing data by dates

My timers list looks like this: timer 1 => { startDate = 17/01/2019 11PM, endDate = 18/01/2019 9AM } timer 2 => { startDate = 18/01/2019 7AM, endDate = 18/01/2019 1PM } timer 3 => { startDate = 18/01/2019 12PM, endDate = 18/01/2019 10PM } time ...

What is the best way to show an element when hovering over another element?

I'm looking for a CSS-only solution (NO JQuery) to display a FontAwsome icon (<i class='fas fa-arrow-alt-circle-left fa-lg arrowbounce text-success hidearrowbounce'></i>) only when hovering over another element. However, despite ...

Manipulate only the elements inside the designated container

My CSS/bootstrap file is quite extensive and the styles are affecting more than just the elements I intended to target. While I want it to have a broad impact, the CSS changes are impacting the entire page. Renaming every element to [name].slider is not ...

To calculate the sum of input field rows that are filled in upon button click using predetermined values (HTML, CSS, JavaScript)

Greetings for exploring this content. I have been creating a survey that involves rows of buttons which, when clicked, populate input fields with ratings ranging from 5 to -5. The current code fills in one of two input fields located on opposite sides of ...

issue with IE's (Internet Explorer) filter invert function not functioning

Why does the filter invert not work in Internet Explorer (IE)? <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> </script> <sty ...

Steps to display a popup notification when a table is modified by an external process

For a project I am working on, I would like to implement a feature where a pop-up message is automatically displayed when a record in the project table is updated by another process. This means that whenever a new record is added, a pop-up message will b ...

CSS - Nesting classes within one another

I'm currently working on customizing a Tumblr theme. Users have the option to choose between a one-column or two-column layout style, and I'm facing some challenges with implementing this in the CSS code. I attempted to add a class based on the u ...

Is javascript or ajax the best choice for updating a database in asp.net mvc?

I need help with updating a row in my database based on a change event from a dropdown list. I am not sure whether to use javascript or ajax for this purpose as I want to avoid page refresh. Any recommendations on which method is best and where I can find ...

Increasing the font size significantly will not change the fluidity of the layout

When I initially didn't set the font-size, and inserted a long text in a div like this: <div>Hello World Hello World Hello World Hello World Hello World Hello World</div> If I narrow the browser, the overflow part would change to the nex ...

Guide on encrypting data on the server with PHP and decrypting it on the client side using JavaScript

I'm currently developing a training website with PHP and I am looking to share my training resources securely without worrying about copyright issues. My plan is to encrypt the documents on the server before sending them, and then have them decrypted ...

Issue with Jquery-UI tabs: Default tab loading twice

Utilizing jqueryui-tabs to create a tabbed user interface, my markup in the MasterPage appears as follows: <div id="channel-tabs" class="ui-tabs"> <ul class="ui-tabs-nav"> <li><%=Html.ActionLink("Blogs", "Index", "Blog", n ...

Updating with the Sequelize query that includes the returning: true option achieves success, yet the return value is undefined

Presented here is the function I utilize to update the URL for a user's profile picture: const changeProfilePicture = async (req, res) => { const userId = req.param("id"); if (userId) { const updatedPath = `...`; User.update( { ...

What is the best way to modify a state in nextjs?

Recently, I've been working on a next.js project that includes a shopping cart feature. Essentially, when you click on an item, its image is added to a list and displayed with all the other selected items. To remove an item, users can simply click on ...

Using `this` in a Jquery get() call to reference a callback function

Utilizing the this keyword in the callbacks of $.get() is my current challenge. The outline of my code looks like this: var myObject = { get: function() { $.get(server,data,function(data,status) { this.callback(); }); }, callback: func ...

Merge Various Ng-Loops

I am working with an HTML structure in which each child has varying lengths: <div ng-repeat='element in treeView'> <div ng-repeat='element1 in element.children'> <div ng-repeat='element2 in element1.chil ...

Using jQuery, you can easily update the value of the nth-child(n) for a cloned element

Looking to duplicate an HTML element and assign new values to its child elements? Here's my current HTML structure: <div id="avator" class="avator" style="display:none"> <label><a href="/cdn-cgi/l/email-protection" class="__cf_email ...

How can you resize an HTML table by dynamically adding or removing rows and columns?

Is there a way to dynamically add or remove rows and columns from an HTML table, also known as resizing it? The table should have a rectangular shape as it will later represent a 2D array value. Since the table will be refreshed frequently and may become ...

Different options for reading large files during an AJAX file upload

It seems that php's file_get_contents is not able to handle large files. What can be done as an alternative if it is causing a "stack overflow" issue? HTML File <form id='test'> <input type='file' name='Receipt&ap ...