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

169
Visualizações
how to get the value of a variable declared within a function

I'm a beginner in JS. In my personal project I want to use a datalist of colors to change the div color.

I managed to do it with select. But it doesn't work with datalist. So I decided to console log the value of the variable declared in the function but I get the error: x is not defined. How to make it work? (It's probably a basic question)

const selectSection = document.querySelector(".select-section");

function myFunction() {
  var x = document.getElementById("my-select").value;
  selectSection.style.backgroundColor = x;
}

console.log(x);
<label for="my-select">Pick a color:</label>
<select name="" id="my-select" value="Choose the background color" onChange="myFunction()">
  <option value="default">default</option>
  <optgroup label="Warm Colors">
    <option value="red">red</option>
    <option value="orange">orange</option>
    <option value="yellow">yellow</option>
  </optgroup>
  <optgroup label="Cool Colors">
    <option value="green">green</option>
    <option value="blue">blue</option>
    <option value="purple">purple</option>
  </optgroup>
</select>

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Two options:

1

const selectSection = document.querySelector(".select-section");

let x;

function myFunction() {
  x = document.getElementById("my-select").value;
  selectSection.style.backgroundColor = x;
}

myFunction()

console.log(x);

2

const selectSection = document.querySelector(".select-section");

function myFunction() {
  const x = document.getElementById("my-select").value;
  selectSection.style.backgroundColor = x;
  return x
}

const x = myFunction()
console.log(x);

Remember to never use var

about 4 years ago · Juan Pablo Isaza Relatório

0

First please don't use the var keyword in your code read this article to know the reason

Second to solve this problem

  1. try to declare your variables in the global scope:

    let x; // in global scope (outside the function)

  2. and assign a value inside the function:

    x = document.getElementById("my-select").value;

about 4 years ago · Juan Pablo Isaza Relatório

0

You can declare the variable outside the scope of the function, but you must make sure to only access that variable AFTER the function has completed, otherwise the code will run BEFORE the function executes and the variable will not have been altered yet.

const selectSection = document.querySelector(".select-section");

let x = null;

function myFunction() {
  x = document.getElementById("my-select").value;
  document.body.style.backgroundColor = x;
  // If this line executes, we know x has been modified, so
  // it's safe to try to access it outside of the function
  showX();
}

function showX(){
  console.log(x);
}
<label for="my-select">Pick a color:</label>
<select name="" id="my-select" value="Choose the background color" onChange="myFunction()">
  <option value="default">default</option>
  <optgroup label="Warm Colors">
    <option value="red">red</option>
    <option value="orange">orange</option>
    <option value="yellow">yellow</option>
  </optgroup>
  <optgroup label="Cool Colors">
    <option value="green">green</option>
    <option value="blue">blue</option>
    <option value="purple">purple</option>
  </optgroup>
</select>

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