Home > Mobile >  Editing HTML input style with JavaScript Array
Editing HTML input style with JavaScript Array

Time:06-08

Im trying to recreate a version of wordle with my own code, and i have each letter set as its own input in html, im using a nested for loop to check to see whether the letter at a certain input is the same as the letter in the correct word and then highlighting it green. My for loop looks like this:

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

answer = "shorts"

for (let i = 0; i < rowIndex1.length; i  ) {
    for (let j = 0; j < answer.length; j  ) {
        if (rowIndex1[i] == answer[j]){
            rowIndex1[i].style.backgroundColor = 'green';
        }
    }
}

Each square that I have defined represents one input, but I can't seem to change the background color of the input box with my last line of code, the only thing I can do is select individual inputs by doing:

document.getElementById("square3").style.backgroundColor = 'green';

but if I do this, the loop is useless, it seems as though I can't use the array in my first line to get through the HTML input elements, is there any way I can edit style in the loop using my rowIndex1 array?

CodePudding user response:

Try this

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

answer = "shorts"

for (let i = 0; i < rowIndex1.length; i  ) {
    for (let j = 0; j < answer.length; j  ) {
        if (rowIndex1[i] == answer[j]){
            document.getElementById(rowIndex1[i]).style.backgroundColor = 'green';
        }
    }
}

This supposes that you have <input id="square3" />

What i would do

<input id="tile_s" />

this way you can use just one loop without a comparative.

for (let j = 0; j < answer.length; j  ) {
    document.getElementById("tile_" answer[j]).style.backgroundColor = 'green';
}

CodePudding user response:

why you are looping answer = "shorts" while its just a single string ?

also you have to give us more of the code to see what those rowIndex1 are referring to and how they are being setup

but assuming they are ID's of inputs you could do this ( press on RunCode bellow to see the result ) :

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

var answer = "shorts";

for (let i = 0; i < rowIndex1.length; i  ) {

         var input = document.getElementById(rowIndex1[i]);  
  
        if (input.value == answer){
            input.style.backgroundColor = 'green';
            }
}
<input id="square1" value="">
<input id="square2" value="shorts">
<input id="square3" value="">
<input id="square4" value="shorts">
<input id="square5" value="">
<input id="square6" value="long">

  • Related