-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!

Lelio Faieta
  • 6,457
  • 7
  • 40
  • 74
mooakk
  • 3
  • 3

2 Answers2

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>
ChazUK
  • 744
  • 4
  • 26
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>
Samball
  • 623
  • 7
  • 22