0

I'm trying to call different javascript functions to run in my html from the selection of radio buttons. I currently have 3 buttons and I want them to run after a button is clicked.

My current HTML is:

<button class="button" onclick="runScript();">Run</button>

<input name="radioButton" type="radio" value="1"> Option 1
<input name="radioButton" type="radio" value="2"> Option 2
<input name="radioButton" type="radio" value="3"> Option 3

I want all 3 options to run separate functions, such as if value="1" then run function 1, etc. It's not a lot but as for my javascript I currently have:

function runScript() {
    var x = document.getElementsByName("radioButton").value;
}

Any ideas on how I can get the functions to run like this?

1 Answers1

0

You could get the value of the selected item with a line like this:

var x = document.querySelector('input[name="radioButton"]:checked').value

instead of:

var x = document.getElementsByName("radioButton").value;

That being said, I would generally not access value until you're sure your query selector found anything, or you'll get an exception.

chad_
  • 3,749
  • 2
  • 22
  • 22
  • You're missing `.value` – Barmar Oct 26 '20 at 21:20
  • thanks.. I'd probably not check the value right where I do the querySelector, but for the sake of the example, it's true.. really we should check if the querySelector found anything, and then get the value. – chad_ Oct 26 '20 at 21:28
  • Using jQuery would make it shorter and also avoid the error of trying to get the property of null. – Barmar Oct 26 '20 at 21:30
  • I'd found my way to the question through the javascript tag and didn't realize it was a jquery question until you just pointed that out. oops. I prefer straight js, but contextually you're right. My bad. – chad_ Oct 26 '20 at 21:31