-2

I'm writing an HTML page for a class project. It needs to show different information based on what the user has selected. I have 5 buttons at the top with onclick that activates a function that should be changing the text inside of the <p> element below them.

I tried switching document.GetElementById('main').innerHTML = link; with alert('link'), and it gave me an empty alert box. I've checked my syntax repeatedly, and the case statement has no errors in it. I know that it isn't an error in the button element or the function itself, because it did give me an empty alert box when I tried the alert statement I mentioned earlier. So I've ruled out every error I can think of.

Below is the code (with most button elements and case statements removed for brevity)

        <script>
            var link = '';

            function TextSwitch(n) {
                switch (n) {
                    case '1':{
                        link = 'Option 1 has been selected'
                        break;
                    }
                }
                document.GetElementById('main').innerHTML = link;
            }
        </script>
    </head>
    <body style='background:#ffffee'>
        <div align='center'>
            <button type=button style='width:10%' onclick='TextSwitch(1)'>Option 1</button>
        </div>
        <p id='main'>text
        </p>
SirFireball
  • 91
  • 1
  • 6

3 Answers3

2

What is happening is that you're passing 1 as a parameter instead of '1'. Your switch is working on strings, and your parameter is an integer. You should change one of them in order to make it work.

Tom O.
  • 5,730
  • 2
  • 21
  • 35
0

Just add .toString within your switch statement (and also remove unnecessary {} as mentioned already).

function TextSwitch(n) {
    switch (n.toString()) {
        case '1':
            link = 'Option 1 has been selected'
            break;
    }
    document.GetElementById('main').innerHTML = link;
}
GenericUser
  • 3,003
  • 1
  • 11
  • 17
0

you hade some problems:

  • there is not GetElementById, it is getElementById
  • you are trying to compare 1(number) to '1'(string) in your switch statement

you can solve this using 2 cases to the same result on the switch or define the proper solution and comparison.

<script>
  var link = '';

  function TextSwitch(n) {
    switch (n) {
      case 1:
      case '1':
        {
          link = 'Option 1 has been selected'
          break;
        }
    }
    document.getElementById('main').innerHTML = link;
  }
</script>
</head>

<body style='background:#ffffee'>
  <div align='center'>
    <button type=button style='width:10%' onclick='TextSwitch(1)'>Option 1</button>
  </div>
  <p id='main'>text
  </p>
Prince Hernandez
  • 3,623
  • 1
  • 10
  • 19