Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

392
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda