0

This is my first project for JS, and I'm tasked with making a table that randomly generates numbers from 1 through 100, and changing the background color of cells that are multiple of 3 to red, and multiples of 2 to blue. I can create the table with random numbers, but don't know how to change the background color of the cell. Here is my code for the table.

  // creates a string var that holds the table
    var str = "<table border='1'>";
    for (row = 0; row < num; row++) {
        str += "<tr>";
        for (col = 0; col < num; col++) {
            str += "<td>";

            // creates a random number from 1-100
            var randNum = Math.floor(Math.random() * 100) + 1;
            str += randNum;

            // if a random num is a multiple of 3
            if (randNum%3 === 0) {

                // make cell have red background

            }
                    // if a random number is a multiple of 2
            else if (randNum%2 === 0) {

                // make cell have blue background

           }
            str += "</td>";
        }
        str += "</tr>";
    }
    str += "</table>";

I tried setting the < td > with an id=" " and then in the if statement calling it like the, but it doesn't work.

               str += "<td id='redOrBlue'>";
            // creates a random number from 1-100
            var randNum = Math.floor(Math.random() * 100) + 1;
            str += randNum;

            // if a random num is a multiple of 3
            if (randNum%3 === 0) {
                // make cell have red background

              document.getElementById('redOrBlue').style.backgroundColor='red';
            }
                    // if a random number is a multiple of 2
            else if (randNum%2 === 0) {
                // make cell have blue background

                document.getElementById('redOrBlue').style.backgroundColor='blue';
           }
            str += "</td>"; 

Any help would be appreciated.

http://pastebin.com/EueJtT9n - Full program code

4
  • 1
    Possible duplicate of changing background color of a table column javascript Commented Apr 2, 2016 at 22:28
  • @AliSeyedi Haha you're right, and it's also been created today - could it be at all possible that both posters are working on the same project? :P Commented Apr 2, 2016 at 23:02
  • @AliSeyedi sorry, I searched for my problem, and that didn't seem to come up. I figured out my problem thanks to 'viiiyears'. Should I delete this? Thanks Commented Apr 2, 2016 at 23:51
  • @Gorgon_Union Probably don't worry too much about deleting it. It'll likely be closed as a duplicate, but if you didn't find the other question, maybe other people will have the same problem and find yours instead. It might be more helpful to leave it, but to let it be closed. Commented Apr 3, 2016 at 0:03

3 Answers 3

0

If you put your td creations into a if else statement you can do it pretty simply like this:

HTML

<div id="mainDiv">
  <input type="text" id="myNo" />
  <input type="button" id="gridSize" value="Show It" />
</div>

<div id="result"></div>

JS

var button = document.getElementById('gridSize');
button.onclick = function(e) {
  result = document.getElementById('result');
  num = parseInt(document.getElementById('myNo').value);
  alert(num);
  if (isNaN(num)) {
    alert("No Numeric Value!");
  } else {
    result.innerHTML = num;
  }
  var str = "<table border='2'>";
  for (row = 0; row < num; row++) {
    str += "<tr>";
    for (col = 0; col < num; col++) {
      var randNum = Math.floor(Math.random() * 100) + 1;
      if (randNum % 2 === 0) {
        str += '<td style="background: red;">';
      } else if (randNum % 3 === 0) {
        str += '<td style="background: blue;">';
      } else {
        str += "<td>";
    }
    str += randNum + "</td>";

    }
    str += "</tr>";
  }
  str = str + "</table>";
  result.innerHTML = str;
}

jsfiddle here

Sign up to request clarification or add additional context in comments.

Comments

0

I would stick with what you had in the first effort you made. Only add in some CSS before you start, with the classes .blue-cell and .red-cell, each with the corresponding background colour.

This will change your logic a little, as you will need to:

1) add the opening "td" to your string

2) generate the number to go inside the cell

3) add " class="red-cell/blue-cell">" to the string

4) add the number to the string

5) close the tag "td"

Comments

0

Try using the following code inside your for loop:

            str += "<td"; //Notice how we leave out the second bracket for now

            // creates a random number from 1-100
            var randNum = Math.floor(Math.random() * 100) + 1;

            // if a random num is a multiple of 3
            if (randNum%3 === 0 && randNum%2 === 0) {
                str += ' style="background-color:purple"';
            } else if (randNum%3 === 0) {
                //Add an inline style to change the background colour
                str += ' style="background-color:red"';
            } else if (randNum%2 === 0) {
                //Add an inline style to change the background colour
                str += ' style="background-color:blue"';
            }
            str += ">" + randNum + "</td>"; //Now we add the missing bracket in here

What this code does is leave the td element open to add attributes to it when we check the condition (the random number).

I tried setting the < td > with an id=" " and then in the if statement calling it like the, but it doesn't work.

When you think about it, it actually makes sense that this doesn't work. id is a property of an element of the DOM (Document Object Model) which is essentially Javascript's way of accessing the webpage. When you try to get the element with the id you gave it, it fails because the element doesn't exist in the DOM - at the moment it's just a string variable.

In order to get this method to work, you would have to add the "table string" to the DOM and then you could access and change the ID properties of the elements. I've made a JSFiddle to mimic your desired behaviour by using the id-modification method.

4 Comments

Thanks for the reply, but it doesn't seem to work. No cells appear at all, it's just a skinny block, without cells, or numbers. Your clarification on why it doesn't work definitely helps me understand my problem more.
Hmm.. I did write it off the top of my head - my bad! I'll chuck it into JSFiddle and fix it up for you; gimme a sec :)
@Gorgon_Union I've fixed it and created JSFiddle: jsfiddle.net/Brads3290/Lkowvxgm to demonstrate the working version. The issue was that I added the random number in the wrong spot, so a 'td' element looked like "<td50 style...> </td>", where 50 is the random number... Thanks for letting me know!
Yeah, it looks like my changes to the code were close to what you just posted. My issue was that I could get the colors to show, but then the numbers weren't showing, due to me not having 'randNum' in the outside of the < td> string. But, this clears things up for me. Thanks for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.