Home > Blockchain >  Changing color of input box inside an Array Javascript
Changing color of input box inside an Array Javascript

Time:06-09

I have an array that includes 6 inputs from my Html.

<input type="text" maxlength="1" style="font-size: 30px; color: white; text-align: center;" onkeyup = "jump001(this, 'square2')" id ="square1" >
    <input type="text" maxlength="1" style="font-size: 30px; color: white; text-align: center;" onkeyup = "jump001(this, 'square3')" id ="square2" >
    <input type="text.css" maxlength="1" style="font-size: 30px; color: white; text-align: center;" onkeyup = "jump001(this, 'square4')" id ="square3" >
    <input type="text.css" maxlength="1" style="font-size: 30px; color: white; text-align: center;" onkeyup = "jump001(this, 'square5')" id ="square4" >
    <input type="text.css" maxlength="1" style="font-size: 30px; color: white; text-align: center;" onkeyup = "jump001(this, 'square6')" id ="square5" >
    <input type="text.css" maxlength="1" style="font-size: 30px; color: white; text-align: center;" id ="square6" >

the array in JS looks like this

var rowIndex1 = [square1, square2, square3, square4, square5, square6]

I've already defined each square as square1 = document.getElementById("square1").value my only issue is that when I want to change the color of the input, I try to do something like this:

rowIndex1[i].style.backgroundColor = 'green';

I have it set up like this because I want to loop it and get it to go through each input and change the color accordingly, but if I don't call a specific square then the color doesn't change. Is there any way to change the color using the code I used above?

CodePudding user response:

document.getElementById('#' rowIndex1[i]).style.backgroundColor = 'green';

Concat string like #square1,#square2,#square3,...

Edit

In array you are store like

square1 = document.getElementById("square1").value;

Change to this

square1 = document.getElementById("square1");

You just store element in arr

After you can use any where

Just like

rowIndex1[i].style.backgroundColor = "green";

CodePudding user response:

you can try it this way:

let rowIndex1 = ['square1', 'square2', 'square3', 'square4', 'square5', 'square6'];
rowIndex1.forEach(el => document.getElementById(el).style.backgroundColor = 'green')
.b1 {
  font-size: 30px;
  color: white; 
  text-align: center;
}
<input type="text"  maxlength="1" id ="square1">
<input type="text"  maxlength="1" id ="square2">
<input type="text"  maxlength="1" id ="square3">
<input type="text"  maxlength="1" id ="square4">
<input type="text"  maxlength="1" id ="square5">
<input type="text"  maxlength="1" id ="square6">

  • Related