Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

387
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda