green9975
green9975

Reputation: 11

if-else change bg color depending what is the letter in the div

I'm doing a crossword puzzle and so I got to the point of having to create conditions ...

I have not found anything that solves my problem

I need a code that when in the input text I put the right letter set bg color "green" and if it is wrong in "red"

<input class="empty" type="text" id="names01" onchange="changeColor()" maxlength="1" /> 

//for example if names01 = "c" set bg color green.....else set bg color to red

if (condition){function changeColor() {
document.getElementById("names01").style.backgroundColor = "green";}}

Upvotes: 0

Views: 178

Answers (2)

mplungjan
mplungjan

Reputation: 178350

The immediate change is to have the condition inside the function and pass the ID to it

function changeColor(id) { 
 if (condition) { 
   document.getElementById(id).style.backgroundColor = "green";
 }
}

You likely want this abstraction. Otherwise you need a lot of conditions

Note I delegate from the container instead of adding an event handler on each field

Also I use "input" instead of "change" since it handles more cases (for example paste)

const solution = {
  "names01": "c",
  "names02": "r"
}


document.getElementById("crosswordContainer").addEventListener("input", function(e) {
  const tgt = e.target;
  if (tgt.type==="text") {
    // conditions
    let myClass = ""; // the word class is reserved
    const val = tgt.value.trim().toLowerCase(); // remove spaces
    tgt.classList.remove("red", "green"); // reset
    if (val) { // something was filled in
      myClass = val === solution[tgt.id] ? "green" : "red"; // this is called a ternary condition
      tgt.classList.add(myClass); // check if myClass is empty, if not, add it
    }
  }
})
.green {
  background-color: green;
}

.red {
  background-color: red;
}
<div id="crosswordContainer">
  <input class="empty" type="text" id="names01" maxlength="1" /> 
  <input class="empty" type="text" id="names02" maxlength="1" /> 
</div>

Upvotes: 0

Ankita Kuchhadiya
Ankita Kuchhadiya

Reputation: 1282

You need to set the condition inside the function to match the value and change the color:

function changeColor(e) {
  let bgColor = e.value === 'c' ? 'green' : 'red';
  document.getElementById("names01").style.backgroundColor = bgColor;
}
<input class="empty" type="text" id="names01" onchange="changeColor(this)" maxlength="1" />

Since, you are passing the reference of the element in the change function you can also use:

function changeColor(e) {
  let bgColor = e.value === 'c' ? 'green' : 'red';
  e.style.backgroundColor = bgColor;
}

Upvotes: 2

Related Questions