Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

391
Views
i cant change my background color with if else statements

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";}
      }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!