-1

I need to basically have five checkboxes, all with different colors. Whatever the user types in after clicking needs to be printed to the screen as successive colors based on what boxes are checked. Ie: If blue and yellow are ticked then the first word will be blue and the second yellow, third blue and fourth yellow.. If three boxes are ticked, a looping trio of colors will be seen and so on up to to 5 boxes!

My plan was to take the text the user wrote and put it into an array. Then using a for loop I want to increment through and use document.createElement('div') and append these words into a container (the parent div) on the body.

function colourCode() {

        var userArray = [];
        var userText = document.getElementById("textArea").value;
        userArray.push(userText);

        var container = document.getElementById("container");
        for (var i = 0; i < userArray.length; i++) {
            var div = document.createElement("div");                

            div.innerHTML = (userArray[i]);                

            container.appendChild(div);

This works fine.

Then I wanted to use an if statement to change the colour if the box is checked.

if (document.getElementById("cbox1").checked === true) {

    document.getElementById("container").style.color = "Blue";

}

This changes the whole sentance blue, even if other boxes are checked. In fact it changes the color to whichever box is checked first.

I thought about somehow implementing a modulus operator that might loop through the checkboxes at the same time the word is appended from the array, but no idea how.

Anyone got any ideas?

Also, jQuery is not an option!

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335

1 Answers1

1

Here is a working snippet.

Push your selected colors inside an array and select them following the index of your words

var container = document.getElementById("container");
var blue = document.getElementById("checkboxBlue");
var yellow = document.getElementById("checkboxYellow");
var red = document.getElementById("checkBoxRed");

function colourCode() {
  container.innerHTML = ""; //Reset text

  //Push all the colors selected
  var colorsArray = [];
  if (blue.checked)
    colorsArray.push("blue");
  if (yellow.checked)
    colorsArray.push("yellow");
  if (red.checked)
    colorsArray.push("red");

  var words = document.getElementById("textArea").value.trim().split(" ");
  for (let i = 0; i < words.length; i++) {
    let color = colorsArray[i % colorsArray.length]; //Take the correct color
    container.innerHTML += "<span style=\"color:" + color + "\">" + words[i] + " </span>"; //Add span with the word in correct color
  };
}
<input type="checkbox" id="checkboxBlue">Blue
<input type="checkbox" id="checkboxYellow">Yellow
<input type="checkbox" id="checkBoxRed">Red
<br>
<textarea id="textArea"></textarea>
<br>
<button onclick="colourCode()">Generate</button>
<div id="container"></div>
Weedoze
  • 13,683
  • 1
  • 33
  • 63