Change the colors of a dynamic row in an HTML table using various options

I have successfully implemented a dynamic table using HTML and JavaScript. However, instead of applying alternate row colors, I want to assign a unique color to each row. How can I achieve this?

<!DOCTYPE HTML>
<html>
    <head>
        <title>Dynamic Page</title>
    </head>


    <body>
        <table>
            <tr>
                <td>Enter Rows</td>
                <td><input type="number" id="txtRows"/></td>
            </tr>
            <tr>
                <td>Enter Columns</td>
                <td><input type="number" id="txtCols"/></td>
            </tr>
            <tr>
                <td colspan="2"><input type="button" id="btnDisplay" value="Display" onClick="createTable();"/></td>
            </tr>
        </table>
        <table id="tbl_DynamicTable" border="1">
        </table>
    </body>

    <script type="text/javascript">
        function createTable()
        {
          debugger;
            var rows = document.getElementById("txtRows").value;
            var cols = document.getElementById("txtCols").value;
            var table = document.getElementById("tbl_DynamicTable");
            var str="";
            for(var i=0;i<rows;i++)
            {
                str += "<tr id=row" + i +">";

                //r = document.getElementById('tbl_DynamicTable').getElementsByTagName('<tr>');
                //r.bgColor = colours[(i%k)/group | 0];

                //mycurrent_row.style.backgroundColor = "#EEF4EA";
                //mycurrent_row.style.backgroundColor =colours[(i%k)/group | 0];

                for(var j=0;j<cols;j++)
                {
                    if(i==0)
                    {
                        str += "<th> Header " + j + "</th>";
                    }
                    else
                    {
                        str += "<td> Row " + i + ", Cell "+ j + "</td>";
                    }
                }
                str += "</tr>             
            }           
            table.innerHTML = str;
        }       


        $("tr").style("bgcolor","red");     
    </script>
</html>

I am unfamiliar with integrating jQuery into an HTML page as I am new to this. Any guidance on how to incorporate it would be appreciated.

Answer №1

If you're looking to generate a random color, there are several ways to do so.

Consider these examples:

JAVASCRIPT

'#' + Math.floor(Math.random() * 16777215).toString(16);

jQuery

(function(m,s,c){return (c ? arguments.callee(m,s,c-1) : '#') +
  s[m.floor(m.random() * s.length)]})(Math,'0123456789ABCDEF',5)

To incorporate the randomly generated hex color into your table row (TR), simply add it as the background color.

HTML

<table border="1">
  <tr bgcolor="#FF0000">
                  ^ Here
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
</table>

For more color code snippets and examples, visit

Answer №2

Here is a JavaScript solution that utilizes jQuery to generate random colors for each row in a table:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function get_random_color() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.round(Math.random() * 15)];
    }
    return color;
}

// Call paint_rows function on document ready
$(function(){
    paint_rows();
});

function paint_rows() {
    $('#table_id tr').each(function(){
            $(this).css('color', get_random_color());
    });
}
</script>

Make sure to customize the colors array with sufficient color values, including hex values.

You can invoke the paint_rows() function whenever necessary.

I hope this explanation proves useful to you.

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

The Ajax operation does not finish before the second one is initiated

My Ajax function is set up like this: function PersonAtlLawUpdate(personRef) { var selectionPanel = $('div#SelectionPanel'); var fromdate = selectionPanel.find('input#FromDateTextBox')[0].defaultValue; var timeSpan = selectionPanel.fin ...

The File Filter feature of Angular's ng2-file-upload is not functioning correctly for PNG files in the Internet Explorer

I am encountering an issue with the file uploader plugin ng2-file-upload when trying to upload a PNG file using Internet Explorer 11. For some reason, the PNG files are not being added to the queue, even though all other allowed file types work perfectly f ...

Mastering asynchronous function handling in Node.js

I'm currently experiencing an issue with printing two statements using two functions var mongoose = require( 'mongoose' ); var_show_test = mongoose.model( 'test' ); exports.showTest = function(req,res) { var jsonString = []; ...

Having trouble retrieving data from mailosaur using protractor, even though it works fine with node.js

I've been trying to incorporate Protractor code with mailosaur for handling email functionality but I'm facing issues retrieving the value while coding in Protractor. Surprisingly, when I run the same code in node.js it works perfectly fine and I ...

Applying CSS styles exclusively to a div element and not its before pseudo-class

So I'm working on an HTML page with a div that looks like this: <div class="get-this"> blah blah </div> I've added a before pseudo-element to the div and now I want to apply a CSS style specifically to the div, not including the pse ...

Displaying Various Items Based on the Language Selected in the Google Translate Widget

Currently, I am in the process of developing a website complete with a shopping cart that will feature different products based on the country of the customer. The client has requested the use of Google Translate to allow for language changes. To accommod ...

What is the best way to properly format the retrieved JSON string using Ext JS?

After receiving the JSON data shown below, I need to change the formatting of the string values in the 'code' field. For example, 'TOTALPENDING' should display as "Pending Bonus" and 'TOTALLEFT' as "Current Bonus". How can I m ...

Only after the code is executed again will $.get function start working

On my main page, I have a select element that is populated from a database with the following code: <select id="report" class="selectpicker input-sm"> <option value=''>Choose a date</option> <?php foreach($this->r ...

fresh map from Google: Coordinates LatLng may not be a number, but my hunch tells me it is

Seeking Assistance with this Issue - For example, the initial location data appears as: "Object Lat: -36.768498 Lng: 174.75895" However, an error is indicating that the latitude is not recognized as a number. Rather than making adjustments without clea ...

Is it possible to change the name of a PHP file using the value entered in an input

I am currently in the process of trying to change the name of a file while uploading it using the JQuery uploader. I have made some progress, and here is the crucial part of my UploadHandler.php: protected function handle_file_upload($uploaded_file, $name ...

How to initiate focus on Angular 2 MdInputContainer after the view has been

I am encountering an issue with setting focus on the first md-input-container element within a component when the view loads. Despite implementing a @ViewChild property and calling focus on it in the ngAfterViewInit method, the focus does not seem to be wo ...

Having trouble sending an ajax request from localhost to a remote server

When attempting to make an ajax request (using jquery) from my local server to a remote page where I am the administrator, I encounter the following error: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin &ap ...

Experiencing difficulties when utilizing Jest to test components

I recently started working with Jest and JavaScript. I wrote a test for one of my components, but it's failing, and I'm struggling to figure out what's wrong (seems like something related to enzyme). Here is the output: ● Console co ...

The hover effect does not function on an SVG element when it is placed within an external file

I've been experimenting with SVG animation. My goal is to change the color of a circle when it's hovered over. <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 437 ...

The age calculator is failing to display the accurate age calculation

This code is designed to compute the age based on the selected value in the combo box, and display the result in the text box below. The age should update every time the user changes the selected value in the combo box. However, the computed age is not cur ...

Stop geocomplete from providing a street address based on latitude and longitude coordinates

Is there a way to prevent geocomplete from displaying the street portion of the address when passing lat and lng coordinates? Here's an example: If I pass these coordinates to geocomplete: var lat = '40.7127744' var lng = '-74.006059& ...

Ways to avoid single-sided border from overlapping with border radius

When adding a 2px bottom border to a text field with a 4px corner radius on the container, the border tends to curl around the edge due to the larger radius. I am looking for a solution to keep the bottom edge flat. [What I DON'T want: border wrappin ...

Make sure to consistently show the rating bubble within the md-slider

I am currently exploring the functionality of md-slider in its md-discrete mode. However, I would like to have the slider bubble always visible on the screen, similar to this: I do not want the slider bubble to disappear when clicking elsewhere. Is there ...

Can anyone provide guidance on locating the parent of a pseudo element with Selenium WebDriver?

Is there a way to retrieve the parent web element of a pseudo element (if we can call it the parent) using JavaScript? I know that Selenium's methods for searching for web elements are not suitable for pseudo elements, but JavaScript does allow manipu ...

Set the div to have a position of absolute, disregarding any other parent divs that may also have position absolute set

Is there a way to bring an outsider class <div> to the front of all others, even when all <div> elements are set as position: absolute;? How can the .free-object, which is inside .left, overlap both .left and .right? I have tried using z-ind ...