Experience the thrill of living in jQuery!

<table style="width: 50%" id="myTable">
 <tbody>
 <tr><td>Row 1</td><td>dd</td><td>red</td><td>dd</td></tr>
 <tr><td>Row 2</td><td>dd</td><td>green</td><td>dd</td></tr>
 <tr><td>Row 3</td><td>dd</td><td>red</td><td>dd</td></tr>
 </tbody>
</table>
<a href="#" name="addRow">Add Row</a>

$(document).ready(function () {        
       $("a[name=addRow]").click(function() {
                $("table#myTable tr:last").after('<tr><td>Row 4</td><td>dd</td><td>red</td><td>dd</td></tr>');
                return false;
        });

    $('#myTable tbody tr td').each(function()
{
    if ($(this).text() == 'red')
    {
        $(this).parent().css('background-color', 'red');
    }
    else if ($(this).text() == 'green')
    {
        $(this).parent().css('background-color', 'green');
    }
});

 });

why does this code not work when adding new rows? I have tried using the live function:

$('#myTable tbody tr td').live('each', function()

but unfortunately, it did not solve the issue.

LIVE: http://jsfiddle.net/pytP2/

Answer №1

This code snippet demonstrates the functionality of adding a new row to a table and applying background colors based on the text content of the cells:

$(document).ready(function () {        

$("a[name=addRow]").click(function() {
    $("table#myTable tr:last").after('<tr><td>Row 4</td><td>dd</td><td>red</td><td>dd</td></tr>');
    initRow($("table#myTable tr:last"));
    return false;
});

$('#myTable tbody tr').each(function()
{
    initRow($(this));
});

function initRow(row)
{
    row.find('td').each(function(){
        var self = $(this);
        var textInTD = $.trim(self.text());
        if (textInTD == 'red')
        {
            row.css('background-color', 'red');
            return false;
        }
        else if (textInTD == 'green')
        {
            row.css('background-color', 'green');
            return false;
        }
    })
}
});

If further explanation is needed, comments can be added to clarify the code.

Answer №2

bind will link a handler to a specific event for all current and future instances of the specified elements, which is not what you're trying to achieve here. You actually need to update the styling of new elements added to the table as they are created. Using bind would only be helpful if you wanted to apply a certain action like 'click' to each new row in your table.

To correct your code, make sure to invoke the style update function after adding each new element. You can see a functioning example here - http://jsfiddle.net/ipr101/zDvAQ/1/

Answer №4

This method may not be effective as the onload code will only trigger once during the initial load...

To ensure the code runs after adding a new row, it is recommended to move the necessary code into a separate function and call it following the addition of the new rows.

For concern over performance issues, especially with large tables, it may be beneficial to pass the newly added row to the function as well.

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

Preventing Unauthorized Script Usage in Jquery $.post and PHP to Safeguard Main Website

With the current setup, my PHP script utilizes Jquery $.post to either return a response or perform an action within the targeted .php file. For example, when a user submits their Name in a form on the page, $.post is triggered and sends the Name field val ...

I'm having a strange issue where my code runs perfectly on JSFiddle, but it refuses to work on localhost

I am facing an issue with running my code on my LAMP server localhost, even though it works fine on JSFiddle. Typically, when this happens, it's usually a small mistake that I overlook. However, having multiple sets of eyes look at the problem is alwa ...

Using Angular 2 to bind to a formControl in a Select2 multiple selection scenario

I have been working on implementing Select2 in my Angular2 application. While I am able to display my selection when choosing the options, I am facing an issue with binding the selected options to my Angular form control. Below is the code snippet from my ...

Issue with MUI DataGridPro failing to sort the email field

I am facing an issue with the sorting functionality in the email field while creating a table using MUI DataGridPro. The sorting works fine for all other fields except for the email field. Adding some random text here to ensure my question is published. Pl ...

What causes the div to not adjust to the browser window when the vertical size is decreased?

Imagine a basic HTML page like this: <doctype> <html> <head> <title>My Amazing Page</title> <script type="text/javascript" src="jquery-1.8.3.min.js"></script> </head&g ...

Using Typescript/JSX to assign a class instance by reference

Looking to access an object's property by reference? See the code snippet below; class Point{ x:number; y:number; constructor(x,y) { this.x=x; this.y=y; } } const a = { first: new Point(8,9), second: new Point(10,12) }; let someBoo ...

Changing the hover color of an Angular Material MD Button

<div class="non-active" layout layout-align='space-around center'> <md-button ng-click="$ctrl.widget.type = 'chart'; $ctrl.validateForm()" layout='column' ng-class="{selIcon : $ctrl.widget.type == ' ...

Can you tell me the standard font size in Internet Explorer 9?

After examining this particular website, I found the default styling used by IE 9. The body selector in particular appears as follows: body { display: block; margin: 8px; zoom: 1; } I would have expected a font-size declaration in this code, but su ...

What is the most efficient method for managing components with dynamic templates and their corresponding data in Vue.js?

I have a question and requirement that I would like to discuss. It involves dynamically rendering templates and data using components. The scenario is as follows: The root Vue instance fetches data from the backend, and let's say the following data i ...

What is the best way to stylize a date using Bootstrap-datepicker?

While this topic is well-known, I have a slightly more complex question regarding it. I have gone through the documentation here. My goal is to display the date in French format (dd/mm/yyyy) and save the value in US format (yyyy-mm-dd). Additionally, I nee ...

Achieving this result in HTML using a jQuery accordion component

Hey there, I'm looking to create a full-height accordion that extends from the bottom to the top of the page, similar to what you see on this website: . I also have a footer positioned below the accordion. The content should load when the page loads ...

Attaching a button to a keypress event in Vue 3.0

I'm currently trying to figure out how to trigger a button when either clicked with the mouse or when a key is pressed. I'm having trouble understanding how components communicate with each other. How can I call the pressDown() function in the Ke ...

The jQuery datatable is functioning correctly, however the button is rendered but is not

Originally, I have a datatable which can be viewed at the following link: The functionality I am experiencing is related to a "DISABLE" button that toggles to "ENABLE" and vice versa upon clicking. However, if you click on the same button after it has alr ...

Should the header include individual CSS and JS files, or should all code be contained within a single CSS and JS file?

As I work on optimizing my website, I find myself juggling multiple plugins that include jQuery plugins with CSS along with my own JavaScript code. Currently, the CSS is spread across separate files for each plugin I have downloaded. When needed on a page ...

Ways to verify if one div in jQuery contains identical text to another div

I need help with a jQuery script to remove duplicate text in div elements Here's the requirement: If div1 contains the text "hi" and div2 also contains "hi", then div2 should be removed Below is my current code snippet: <script src="https:/ ...

Is there a specific method or function that can effectively translate special characters such as into their corresponding representations?

When a user provides input for my script using shell arguments, it would look something like this: Kek kek\nkek\tkek\x43 After receiving the input, Javascript interprets my parameter in a specific way: var parameter="Kek kek\&bs ...

Incorporate a checkbox that dynamically changes with the input type number

I'm trying to figure out how to dynamically add checkboxes when the input type number is changed. Currently, I have the following HTML code: HTML CODE <label for checkbox_number>Number of checkboxes :</label> <input id="checkbox_numb ...

Aligning the start date and end date

Since this morning, I've been struggling to align the start date and end date properly, but I can't seem to get it right. The blocks representing the start and end dates are not aligning as they should, unlike the other blocks on the page. I&apo ...

Obtain the user's geolocation in React/Redux by utilizing a promise, then send the position to the action creator through dispatch

Within my store.js, I am attempting to retrieve the end user's geolocation from the browser and then dispatch an action creator. However, this functionality is not being executed as expected. function showPosition(position) { console.log("showPos ...

Turn off the Ripple effect on MUI Button and incorporate a personalized touch

I am trying to create a custom click effect for the MUI Button by removing the default ripple effect and implementing my own shadow effect. I have disabled the ripple using disableRipple, but I am facing issues in applying the shadow effect when the user c ...