Home > Mobile >  i cant change my background color with if else statements
i cant change my background color with if else statements

Time:03-10

Im trying to make a function where I change the background color to the color that is input. It seems like the function works but it only changes to yellow. It leads me to believe that theres something wrong with the if else statements but I cant figure it out.

var colore = document.getElementById("colors");

    function changecolor() {
     if (colore = "yellow"){
      document.body.style.backgroundColor = "yellow";
     }else if (colore = "blue"){
      document.body.style.backgroundColor = "blue";
     }else if (colore = "green"){
      document.body.style.backgroundColor = "green";
     }else if (colore = "black"){
      document.body.style.backgroundColor = "black";
     }else {document.getElementById("error").innerHTML =
        "Enter a Valid Color";}
      }

CodePudding user response:

Your code has a few errors which I have fixed and the details are below

  1. To get the input value, you need to access .value like document.getElementById("colors").value
  2. You need to get the value of text box inside the function all the time
  3. you need to use === in your condition to compare. Single = is an assignment operator, and your code was just assigning yellow each time. Also read Which equals operator (== vs ===) should be used in JavaScript comparisons?

Working Code below

function changecolor() {
  var colore = document.getElementById("colors").value;

  document.getElementById("error").innerHTML=""; // remove existing error

  if (colore === "yellow") {
    document.body.style.backgroundColor = "yellow";
  } else if (colore === "blue") {
    document.body.style.backgroundColor = "blue";
  } else if (colore === "green") {
    document.body.style.backgroundColor = "green";
  } else if (colore === "black") {
    document.body.style.backgroundColor = "black";
  } else {
    document.getElementById("error").innerHTML =
      "Enter a Valid Color";
  }
}
<input id="colors" type="text" />
<button onClick="changecolor()">Change</button>
<p id="error"></p>

  • Related