Modify the background color of a cell to red using jQuery when the value is negative

In the interactive form below, users can dynamically add or remove rows. The calculation involves determining the difference between the cost price and the selling price of a product.

What I have been attempting to do (unsuccessfully for the past week) is to change the background color of the result cell to red if the value is negative and green if the value is positive. Despite finding several solutions on this site, I have been unable to successfully implement them.

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="utf-8">
    <title>CSS</title>
    </head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script>
        function addRow(tableID) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    if (rowCount < 5) { // limit the user from creating fields more than your limits
        var row = table.insertRow(rowCount);
        //var row = table.insertRow(rowCount-1);
        var colCount = table.rows[0].cells.length;
        row.id = 'row_'+rowCount;
        for (var i = 0; i < colCount; i++) {
            var newcell = row.insertCell(i);
            newcell.outerHTML = table.rows[0].cells[i].outerHTML;            
        }
       var listitems= row.getElementsByTagName("input")
            for (i=0; i<listitems.length; i++) {
              listitems[i].setAttribute("oninput", "calculate('"+row.id+"')");
            }
    } else {
        alert("Maximum 5 Rows Only.");

    }
}

function deleteRow(tableID) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    for (var i = 0; i < rowCount; i++) {
        var row = table.rows[i];
        var chkbox = row.cells[0].childNodes[0];
        if (null !== chkbox && true === chkbox.checked) {
            if (rowCount <= 1) { // limit the user from removing all the fields
                alert("Cannot Remove all the Records.");
                break;
            }
            table.deleteRow(i);
            rowCount--;
            i--;
        }
    }
}

    </script>
    <script>
    function calculate(elementID) {
        var mainRow = document.getElementById(elementID);
        var num1 = mainRow.querySelectorAll('[name=num1]')[0].value;
        var num2 = mainRow.querySelectorAll('[name=num2]')[0].value;
        var result = mainRow.querySelectorAll('[name=result]')[0];
        var result1 = num2 - num1;
        result.value = result1;

        // Add logic here to change the background color based on result value

        if(result1 < 0){
            result.style.backgroundColor = "red";
        } else {
            result.style.backgroundColor = "green";
        }

    }
    </script>
    <body>
    <input type="button" value="Add" onClick="addRow('dataTable')" />
    <input type="button" value="Remove" onClick="deleteRow('dataTable')" />
    <table id="dataTable" class="form" border="1">
        <tbody>
            <tr id='row_0'>

                    <td><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>

                    <td>
                        <label>Cost Price</label>
                        <input type="text" size="1" required="required" name="num1" class="num1" id="num1" oninput="calculate('row_0')"/>
                    </td>
                    <td>
                        <label>Selling Price</label>
                        <input type="text" size="1" required="required" name="num2" class="num2" id="num2" oninput="calculate('row_0')"/>
                    </td>
                    <td>
                        <label>Difference</label>
                        <input type="text" size="1" required="required" name="result" class="result" id="result" />
                    </td>

            </tr>
            </tbody>
            </table>
    </body>
    </html>

Answer №1

Despite the HTML concerns (as pointed out in the comments of your query), you can reach your objective by verifying if the result1 variable is larger than zero and then applying the appropriate style to the parent td element of the input. Give this a try:

function calculate(elementID) {
    var mainRow = document.getElementById(elementID);
    var num1 = mainRow.querySelectorAll('[name=num1]')[0].value;
    var num2 = mainRow.querySelectorAll('[name=num2]')[0].value;
    var result = mainRow.querySelectorAll('[name=result]')[0];
    var cell = result.parentElement;
    var result1 = num2 - num1;
    result.value = result1;

    var cellBackground = result1 < 0 ? 'red' : 'transparent';
    cell.style.backgroundColor = cellBackground;
}

Check out this sample fiddle

Answer №2

function calculateValues(id) {
    var row = document.getElementById(id);
    var number1 = row.querySelectorAll('[name=num1]')[0].value;
    var number2 = row.querySelectorAll('[name=num2]')[0].value;
    var output = row.querySelectorAll('[name=result]')[0];
    var difference = number2 - number1;
    output.value = difference;
    if(difference < 0){
        $(output).parent().css("background", "red");
    }else{
        $(output).parent().css("background", "");
    }
}

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

Creating a responsive design with dual backgrounds using Tailwind CSS

I have a design in Figma that I want to convert to React using Tailwind CSS while maintaining 100% pixel-perfect accuracy. The design is created for a Macbook Pro 16 inch, which has a width of 1728px. However, I want to center the content within a customiz ...

What sets Fetch Promise apart in terms of delivery success?

Struggling with using strapi in my project, as the fetch function returns a promise instead of JSON data This is my code : const [products, setProducts] = useState([]); useEffect(() => { (async () => { try { l ...

How does the emoticon code work in Facebook chat?

Just came across this hilarious website here. LOL! I noticed that on Facebook chat, you can insert emoticon photo codes along with text, just like some kind of Facebook API code. With the help of the FB Photo Zoom Google Chrome plug-in, I discovered that ...

What is the best way to incorporate ngRoute into Jasmine / Karma for testing AngularJS applications?

I am currently working on setting up a basic unit test example. Everything is running smoothly with this app.js: var whapp = angular.module('whapp', []) .filter('reverse', [function(){ return function(string){ return string ...

Customize border color for a single cell in a table using Bootstrap 4

I'm facing an issue where I'm trying to apply a red border color to a specific cell, but it's not appearing on the top and left sides of the cell. It seems like the border color of other cells is taking precedence over the one I'm tryin ...

What is the best way to incorporate this code snippet into an object's value?

Is there a way to merge the headStyles object into the headText object? I have already injected the headStyles object into headConfig. import { makeStyles } from '@material-ui/core' const headStyles = { backgroundColor:'green', ...

Customizing Vue: Implementing an automatic addition of attributes to elements when using v-on:click directive

We are currently working with single file Vue components and we're facing a challenge in our mousemove event handler. We want to be able to determine if the target element is clickable. Within our Vue templates, we utilize v-on directives such as: v- ...

Exploring the capabilities of jQuery in conjunction with HttpHandlers

I'm encountering an issue trying to retrieve HTML from a HttpHandler through jQuery. Below is the jQuery script I am using to call the handler: $.get('http://localhost:56964/LoadComments.axd?storyID=' + storyID ,function(data) { alert(data) ...

Can you explain the process of implementing a conditional render with three parts in React?

Currently, I am attempting to implement a conditional render but encountering some issues. Is it achievable? location: `${props.off_campus_location ? ( `${props.off_campus_location}` ) : ( `${props.campus_location.name}` ) : ( `${props.location_type}` )}` ...

Merge the values of the obscured inputs into a JSON-formatted string within a designated concealed input field

Is there a way to merge the hidden input values into a JSON formatted string and store it in a separate hidden input field? <c:forEach var="perForm" items="${importedPersonForms}" varStatus="count"> <input type="hidden" name="importedPerson ...

Angular 14's "rootItem" animation trigger was created with the following alerts: - The properties listed below are not animatable: overflow

Upon upgrading to Angular 14, I encountered this warning. The properties mentioned are not actually used in my animations. [Error in console][1] The animation triggers "rootItem" has been built with the following warnings: - The following provided propert ...

Creating a diagonal rectangle with a flat bottom: A step-by-step guide

Hey there, I've encountered a little issue. I managed to create a diagonal shape on my webpage similar to the one shown in this image: https://i.sstatic.net/tMgpd.png Now, what I'm aiming for is something like this: https://i.sstatic.net/xToz7.p ...

Codeigniter's dynamic auto-complete feature using Ajax

Implementing AJAX Autosearch <script type="text/javascript" src="js/jquery-1.8.0.min.js"></script> <script type="text/javascript"> function ajaxSearch() { alert('hello'); var input_data = $(&ap ...

Close the Bootstrap burger menu after clicking on a scrollspy link

Is there a way to automatically collapse the Bootstrap burger menu when clicking on a scrollspy link? While browsing my website on a mobile device, the Bootstrap navigation menu switches to a burger icon. However, when you click on an internal link that l ...

Puppeteer App Error: An error has been detected on the client side

I am facing an issue using Puppeteer with NEXT.JS while attempting to capture a screenshot. Everything runs smoothly on localhost, but in production, the captured image comes back with the following error message: Application error - a client-side exceptio ...

Performing a $.POST request on a Squarespace webpage

I created a custom form on my website for booking appointments, and it posts to a third-party server. When I submit the form using the <form> tag, I receive the email notification. However, I want to submit the form using $.POST so that I can customi ...

Bizarre actions with jQuery append in Internet Explorer 8

Issue with adding elements to a div in IE8: The element is not added until the button is clicked twice, resulting in two new elements being added at once. Here's the code snippet in question: $(options.addButton).click(function(event) { var proto ...

Why is React's nested routing failing to render properly?

click here for image portrayal I am currently attempting to integrate react router, specifically a nested router. However, when I click the links on the contact page, no results are being displayed. Any assistance would be greatly appreciated. For more in ...

What could be the reason why the navbar ul li a instance is not appearing in Bootstrap 4 modal when using an

Can anyone help me solve the issue I'm having with viewing HTML in a Bootstrap 4 modal? Everything shows up except for the navbar ul li a elements. I've searched for a solution everywhere, but haven't found one yet. Please assist! (I want t ...

Leveraging Enums in Angular 8 HTML template for conditional rendering with *ngIf

Is there a way to implement Enums in an Angular 8 template? component.ts import { Component } from '@angular/core'; import { SomeEnum } from './global'; @Component({ selector: 'my-app', templateUrl: './app.componen ...