Search code examples
javascripthtmlfunctioncss-selectorstextbox

How to use a function to change every textarea?


I don't know, but I think there's probably a problem between the CSS selector and the JS function. I want to change the colors of the textarea and it's attributes (background color, color, and placeholder), which is something in can ✓ off the to do list.

However, for some reason it refuses to apply to any other textboxes. So it's just the already established preset values of the attributes. And I'm having issues with changing the values of input[type="text"] with a function, even when I use querySelector(). Here, check this out.

var bgColors = ["#FFFFFF", "#80C040", "#00FFFF", "#000000", "#000000"];
var textColors = ["#000000", "#000000", "#000000", "#FF0000", "#FFFF00"];
var phColors = ["#808080", "#406020", "#008080", "#800000", "#808000"];
var idx = 0; //index
function setColor() {
  if (idx == 4) {
    idx = 0;
  } else {
    idx = idx + 1;
  }
  document.querySelector('input[type=text]').style.backgroundColor = bgColors[idx];
  document.querySelector('input[type=text]').style.color = textColors[idx];
  document.querySelector('input[type=text]').style.setProperty("--c", phColors[idx]);
}
::placeholder {
  color: var(--c, #808080);
}

input[type="text"] {
  background-color: #FFFFFF;
  color: #000000;
}
<input type="text" placeholder="Type Here">
<input type="text" placeholder="Type Here">
<button onclick="setColor()">change</button>


Solution

  • Use querySelectorAll() and loop over the result.

    var bgColors = ["#FFFFFF", "#80C040", "#00FFFF", "#000000", "#000000"];
    var textColors = ["#000000", "#000000", "#000000", "#FF0000", "#FFFF00"];
    var phColors = ["#808080", "#406020", "#008080", "#800000", "#808000"];
    var idx = 0; //index
    function setColor() {
      if (idx == 4) {
        idx = 0;
      } else {
        idx = idx + 1;
      }
      document.querySelectorAll('input[type=text]').forEach(el => {
        el.style.backgroundColor = bgColors[idx];
        el.style.color = textColors[idx];
        el.style.setProperty("--c", phColors[idx]);
      });
    }
    ::placeholder {
      color: var(--c, #808080);
    }
    
    input[type="text"] {
      background-color: #FFFFFF;
      color: #000000;
    }
    <input type="text" placeholder="Type Here">
    <input type="text" placeholder="Type Here">
    <button onclick="setColor()">change</button>