-1

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

RonyD Kid
  • 83
  • 2
  • 8
  • 2
    use `document.querySelector('input[name="whateverNameYouHave"]:checked').value;` to get the value associated with the checked radiobutton – Seblor Apr 30 '18 at 08:26
  • 1
    Possible duplicate of [How to get the selected radio button value using js](https://stackoverflow.com/questions/3869535/how-to-get-the-selected-radio-button-value-using-js) – t.niese Apr 30 '18 at 08:27
  • There are various questions on SO that target each aspect of your question. So you should show a minimal running code with a specific problem you have. Without that it is not clear where exactly you problem is. Do you have a problem getting the selected radio button? Do you have a problem passing the value of the selected radio button to the switch statement? Do you have a problem to listen to the submit even? .... – t.niese Apr 30 '18 at 08:30
  • I actually don't have a problem, I'm just wondering on how to do it since like I said, I'm fairly new. – RonyD Kid Apr 30 '18 at 08:32

1 Answers1

0

Let's say you have this HTML:

<form id="myForm">
  <input type="radio" name="rand" value="1" />
  ...
  <input type="radio" name="rand" value="5" />
  <button>Submit</button>
</form>

What you can do in JS is listening to onsubmit event and then get the form values you want. When you have them, you can simply use the radio value (rand) in a switch statement.

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

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

    switch(Number(radioValue)) {
      case 1: // do something
      default:
    }
 });
Václav Zeman
  • 606
  • 7
  • 21