Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading