Switch statements with radio buttons

I’m fairly new to JavaScript and I need a bit of help.

I’ve searched for a while on this topic and couldn’t find anything. I’m creating a random quote generator and I need to make it so that the user can pick from a radio input ranging from 1 to 5.

So my question is, can I somehow connect radio buttons with switch statements in JS, so when the user for example picks “one” and then submits, he gets one quote displayed on the screen? This needs to be done only with JavaScript, so no Jquery


Html code:

<form id="myForm">
            <label class="radio-inline">
              <input type="radio" name="optradio" value="1"> One
            </label>
            <label class="radio-inline">
              <input type="radio" name="optradio" value="2"> Two
            </label>
            <label class="radio-inline">
              <input type="radio" name="optradio" value="3"> Three
            </label>
            <label class="radio-inline">
                <input type="radio" name="optradio" value="4"> Four
              </label>
              <label class="radio-inline">
                <input type="radio" name="optradio" value="5"> Five
              </label><br><br>
              <button type="button" class="btn btn-primary btn-lg" value="submit" id="submit">Submit</button>
          </form>```



----------
JavaScript code: 

document.querySelector(“#myForm”).addEventListener(“submit”, e => {
e.preventDefault()

const radioValue = document.querySelector('input[name=optradio]:checked').value;

switch(Number(radioValue)){
    case 1:
      for (var i= 0; i<1; i++) {
        console.log(quoter());
      }
      break;
    case 2:
      for (var i= 0; i<2; i++) {
          console.log(quoter());
      }
      break;
    case 3: 
      for (var i= 0; i<3; i++) {
          cosnole.log(quoter());
      }
      break;
    case 4: 
      for (var i= 0; i<4; i++) {
          console.log(quoter());
      }
      break;
    case 5: 
      for (var i= 0; i<5; i++) {
          console.log(quoter());
      }
      break;
      default: alert('Please pick a number of quotes you would like to see');
    
}

});

Note that the "quoter" is a predefined function.

There is no need to use a switch statement since you always loop over the selected number …
And the default case is never used due to your script throwing an error if nothing is selected (cannot read property value of null).

1 Like

Alright, thanks for your response!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.