-3

I've been trying to figure out how to make it so when someone clicks an option, a variable gets assigned. Here is what I've tried:

function changessw() {
  switch (document.getElementById("ssw").value) {
    case "1":
      var test = "Im A";
      break;
    case "2":
      var test = "Im B";
      break;

  }
}
document.write(test)
<select name="ssw" id="ssw" onchange="changessw()">
  <option value="1">A</option>
  <option value="2">B</option>
</select>

The variable only works when I test it in the function. I want to work globally. Any help would be appreciated!

1
  • 1
    The var test must be declared outside the function. Commented May 24, 2022 at 14:59

2 Answers 2

0

Move your variable declaration outside the scope of the function.

var test;
function changessw() {
  switch (document.getElementById("ssw").value) {
    case "1":
      test = "Im A";
      break;
    case "2":
      test = "Im B";
      break;

  }
  console.log(test);
}
<select name="ssw" id="ssw" onchange="changessw()">
  <option value="1">A</option>
  <option value="2">B</option>
</select>

Sign up to request clarification or add additional context in comments.

Comments

0

Declare the variable outside of the function and then assign it inside the function.

Here's a link to an article on scope in javascript https://www.digitalocean.com/community/tutorials/understanding-variables-scope-hoisting-in-javascript and the MDN entry on let.

let test;

function changessw() {
  switch (document.getElementById("ssw").value) {
    case "1":
      test = "Im A";
      break;
    case "2":
      test = "Im B";
      break;

  }
}

function logTest() {
  console.log(test);
}
<select name="ssw" id="ssw" onchange="changessw()">
  <option value="1">A</option>
  <option value="2">B</option>
</select>
<button onclick="logTest()">Log test</button>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.