-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,242
  • 6
  • 38
  • 64
mooakk
  • 3
  • 3

3 Answers3

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
  • 575
  • 2
  • 22
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
  • 558
  • 3
  • 18
0

You can declare your variable test outside the function and assign the value within function itself.

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

  }
}
<select name="ssw" id="ssw" onchange="changessw()">
  <option value="1">A</option>
  <option value="2">B</option>
</select>
manikant gautam
  • 3,288
  • 1
  • 16
  • 26