using javascript to dynamically color rows in a table based on the value in the status field

Hi, I'm new to javascript and seeking help for my table coloring issue. I have a dynamic table where data is inserted through an Ajax call. The goal is to color specific records based on their status.

I attempted a solution but only one record gets colored while multiple records should be highlighted. Each row's color should change according to the 'status' property received via Ajax call.

Below is the code snippet:

<div class="tb TBN" style="height:125px; border:none;">
    <table class="table table-condensed nchild customer" id="records_table">
        <tbody>

        </tbody>
    </table>
</div>

$.map(data.response.data, function(item) {
    var stat = item.status;
    if (stat == 'A') {
        trHTML += '<tr bgcolor="#0072B5" id="' + item.rCOxylane + '">' +
            '<td align="center" width="5%"> <input type="radio" id="radio" class="radioDetails" name="empdetails" checked="checked" value="' + item.rCOxylane + '"/> </td>' +
            '<td id="decId" style="word-wrap:break-word;">' + item.rCOxylane + '</td>' +
            '<td id="activeId" style="display:none;"> ' + item.status + ' </td>' +
            '<td id="fname">' + fname + '</td>' +
            '<td id="lname">' + item.name2 + '</td>' +
            '<td id="mob">' + item.rCMobile + '</td>' +
            '<td id="emailid" style="word-wrap:break-word;">' + item.rCEmail + '</td>' +
            '<td id="landLine">' + item.rCLandline + '</td>' +
            '<td id="zipCode">' + item.rCZipcode + '</td>' +
            "<td><a id='EditCustomer' class='EditDetails' href='#EditDetails' role='button' data-backdrop='static' data-toggle='modal'>Edit Details</a></td>" +
            '</tr>';
    } else {
        trHTML += '<tr id="' + item.rCOxylane + '">' +
            '<td align="center" width="5%"> <input type="radio" id="radio" class="radioDetails" name="empdetails" checked="checked" value="' + item.rCOxylane + '"/> </td>' +
            '<td id="decId" style="word-wrap:break-word;">' + item.rCOxylane + '</td>' +
            '<td id="activeId" style="display:none;"> ' + item.status + ' </td>' +
            '<td id="fname">' + fname + '</td>' +
            '<td id="lname">' + item.name2 + '</td>' +
            '<td id="mob">' + item.rCMobile + '</td>' +
            '<td id="emailid" style="word-wrap:break-word;">' + item.rCEmail + '</td>' +
            '<td id="landLine">' + item.rCLandline + '</td>' +
            '<td id="zipCode">' + item.rCZipcode + '</td>' +
            "<td><a id='EditCustomer' class='EditDetails' href='#EditDetails' role='button' data-backdrop='static' data-toggle='modal'>Edit Details</a></td>" +
            '</tr>';

    }
});

The problem I am facing is that only one record with status 'A' is being colored instead of all matching records. Any advice or assistance would be highly appreciated. Thank you in advance!

Answer №1

Here are a few issues with the code provided:

  • The JavaScript code should be enclosed within <script></script> tags:

    <script type="text/javascript">
        $.map( data.response.data, function( item ) {    
            var stat = item.status;    
            if(stat=='A'){
                //actions to take if true
            }
            else {
                //actions to take if false
            }
        });
    </script>
    

    Alternatively, you can import it from another file:

    <script type="text/javascript" src="/path/to/your/script.js" />
    
  • There is redundancy in the code. If the main goal is to change the background color of a specific element, it is more efficient to operate on a fragment and concatenate later instead of rendering all the code twice for both conditions:

    <script type="text/javascript>
        //Assuming jQuery is already loaded
        //Wrap it in $(document).ready() if you need JS execution after HTML load
        $(document).ready(function() {
            $.map( data.response.data, function( item ) {    
                var stat = item.status;
                var color_frag = '';
                if(stat=='A'){
                    color_frag='bgcolor="#0072B5" ';
                }
                trHTML = '<tr '+color_frag+'id="'+item.rCOxylane+'">';
                    //Cell content here. Avoid duplicating IDs!
                trHTML+= '</tr>';
                $('.fillthis').append(trHTML);
            });
        });
    </script>
    
    <div class="tb TBN" style="height:125px; border:none;">
      <table class="table table-condensed nchild customer" id="records_table">
        <tbody class="fillthis">
    
        </tbody>
      </table>
    </div>
    

If you need to render multiple rows this way, consider using loops. Rendering duplicate IDs as done in the code will cause issues. As mentioned by @D4V1D, each element in the DOM must have a unique ID. Use classes for referencing multiple elements simultaneously or concatenate unique IDs for individual cells if necessary. Additionally, research the powerful DOM referencing methods available in jQuery.

Additionally, move all styling attributes to CSS files for efficiency, reducing redundancy, and easier code maintenance.

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 significance of the appearance of the letters A and J in the console for Objects?

After running console.log() in JavaScript code, you may notice some random letters like A and j before or after the Object description in the Google Chrome browser console. What is the significance of these letters? ...

When making an Ajax request, the response is received successfully, however, the success, complete, and error

I am attempting to retrieve SQL results from a database using an AJAX call and display them on another PHP page. Here is my AJAX call code: function newfunc(){ start += 10; var params = parseURLParams(document.URL); var datastring = "nextStart="+start+"&a ...

Prevent selection on all elements except for input fields with the type of text

I am facing a challenge where I need to prevent selection on a website page for everything except input[type=text] elements. The answer provided in this accepted response to a similar query almost solves the issue. However, it doesn't stop users from ...

Retrieving JSON data through HttpClient in Angular 7

I am attempting to retrieve information from this specific URL. The data obtained from this URL is in JSON format. This particular file is named data.services.ts: import { Injectable } from '@angular/core'; import { HttpClient } from '@an ...

I am experiencing an issue with the display inline feature not functioning properly in Firefox

I am working with Html code: <div class="login"> <form class="form-horizontal signin"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">Ema ...

Utilizing React and Material-UI to Enhance Badge Functionality

I am exploring ways to display a badge icon when a component has attached notes. I have experimented with three different methods and interestingly, the results are consistent across all of them. Which approach do you think is the most efficient for achiev ...

How can I dynamically update a React/Next.js page as the server completes different stages of a complex action?

Currently, my aim is to develop a single-page application that relies on one major back-end process. This procedure is initiated by a singular string input. The various stages involved and the outcomes are as follows: It takes about 20ms to display/render ...

Learn how to insert JavaScript code into the head of an iframe using jQuery

My goal is to inject javascript code into the head of an iframe using jquery with the code provided below. var snippets_js='<?php echo $snippets_javascript;?>'; var scriptjs = document.createElement("script"); scriptjs.type = "text/j ...

Creating dynamic <a> tags using JavaScript

My current view includes a div tag with 2 links - one for displaying the page in English and another for Arabic. I want to modify it so that if the page is already in English, only the Arabic <a> tag will show, and vice versa if the page is in Arabic ...

Changing json into another format

I am struggling with a JSON data format issue. I have tried using Object.values and object.keys along with Array.prototype.map(), but my algorithm is not producing the desired outcome. [ { "2018-01-01": [ { "firstname": "mati", "lastname": "mati ...

ExtJS web displays appear differently when viewed on Chrome's toggle device mode versus a mobile browser

Greetings, I have been working on developing a web application that can be accessed through a mobile browser. Initially, I created the web application and tested it in mobile mode using Chrome's simulation feature. However, when I tried accessing th ...

What is the reason behind the changes in the CSS rendering behavior of Fieldset legends over the past few months?

A form on my website contains nested <fieldset> elements, each with a unique <legend>. Recently, I discovered an issue with the page rendering on various browsers (Chrome, Firefox, Opera) that was not present before. One element, <span clas ...

`"Attempting to access keys of a non-object value" - Dealing with JSON and React Native`

Having trouble with React Native and JSON structure? No worries, we've all been there at some point! Don't sweat it if you're still new to React and JavaScript - we're here to help! Let's take a look at the JSON structure causing ...

"Create a flexible CSS grid with a dynamically changing number of rows and customizble

I am currently working on a project that involves creating a dynamic grid layout with two resizable columns, namely #red-container and #green-container. The goal is to make each column resizable horizontally while also allowing the main container #containe ...

What is the best way to obtain the current date in JavaScript in the format Mon-DD-YYYY?

Need help with getting the current date in Mon-DD-YYY format using JavaScript. I want to input today's date without the time into a date picker field. My current code is giving errors, below is what I have: Page.prototype.clickOnsessionDate = async f ...

Is there something I'm overlooking in my image navigation? It doesn't seem to be interactive

Looking for assistance regarding the issue below. I can't seem to make my image clickable, and I'm not sure what's causing this problem. <img src= "makeup.html.jpg" alt= "Make up by Lauren Evans logo" title= "Make ...

PHP regular expression that identifies a specific HTML element

Similar Question: Effective ways to parse HTML using PHP I am currently creating a custom WordPress template for a client that requires a PHP function to extract specific HTML tags as defined by the function. For instance, if I input "div" into the f ...

Can the title of a page be modified without using HTML?

Is it possible to update the title of my website directly from the app.js file? (I am utilizing node.js and express.js) ...

How to assign a global variable in Angular 2 from within a promise

I have encountered a strange issue while trying to assign a response to a global variable inside an observable. Here's the logic of my program: Fetch the latest playlists IDs from elastic search (using a type definition file for elastic search). T ...

Is there a way to delete added information using a trigger that has been inserted through ajax?

I created a function in jQuery and Ajax to add information from a separate PHP file to another file. Let's name the destination file "Homepage" and the file with the data "Template". Here is the function I used: var box = $('#infoPageContainer& ...