0

Could anyone please provide a JSFiddle Demo for me with an implementation? I have the following HTML code below. I want to record in an array in javascript the the radio button I clicked. Say if I choose the first radio button id="white1", the array should store the integer '1'. I am a beginner in javascript so any help would be appreciated!

<body>
    <div id="container">
      <div id="overlay">
        <form action="">
          <input type="radio" name="white" value="1" id="radio1"/>
          <input type="radio" name="white" value="2" id="radio2"/>
          <input type="radio" name="white" value="3" id="radio3"/>
          <input type="radio" name="white" value="4" id="radio4"/>
          <input type="button" id="continue" value="Continue"/>
        </form>
      </div>
      <div id="base">
        <video controls>
          <source src="videos/event_0_Junli_Standing_20150322_181647_00_0.6.mp4" type="video/mp4">
          Your browser does not support the video tag.
        </video>
      </div>
    </div>
    <script>
      var arr = []
      document.getElementById("continue").addEventListener("click", function() {
          var cbChecked = document.querySelectorAll('[name="white"]:checked')
          if (cbChecked != null) {
            arr.push(cbChecked.value)
          }
          console.log(arr)
      }) 
    </script>
  </body>
Alex Ker
  • 55
  • 2
  • 10

1 Answers1

1

You can use document.querySelector() to directly select whichever radio button is currently :checked:

var arr = []

document.getElementById("continue").addEventListener("click", function() {
  var cbChecked = document.querySelector('[name="white"]:checked')
  
  if (cbChecked != null) {
    arr.push(cbChecked.value)
  }

  console.log(arr)
})
<form action="">
  <input type="radio" name="white" value="1" />
  <input type="radio" name="white" value="2" />
  <input type="radio" name="white" value="3" />
  <input type="radio" name="white" value="4" />
  <input type="button" id="continue" value="Continue"/>
</form>

.querySelector() returns null if no elements match the supplied selector, otherwise it returns the first element that matches (in your case there would be only one). Note that according to MDN, the :checked selector won't work in browsers older than IE9, in which case you might have to use document.querySelectorAll('[name="white"]') or some other element selection method to get a list of all of the radios and then loop through them till you find the one that is checked.

Note also that I've changed your HTML to a more "normal" implementation of radio buttons, that is, giving them all the same name attribute so that they work as a group, and giving them a value attribute to distinguish between them. They don't need id attributes - at least, not for this.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • Do you think--https://stackoverflow.com/questions/596351/how-can-i-know-which-radio-button-is-selected-via-jquery--works better in terms of compatibility? – Alex Ker Jul 07 '17 at 03:23
  • That other question asked for, and received, jQuery-based solutions, so you can't use those unless you include the jQuery.js library on your page. I've updated my answer slightly with links to some documentation at MDN. What I've shown should work in all current browsers, and in older browsers back as far as IE9. – nnnnnn Jul 07 '17 at 03:28
  • Any reason not to grab the value "old school" using the forms collection: `var cbCheckedVal = document.forms[0]["white"].value;`? I'm guessing it would be more efficient than `querySelectorAll`, though not neccesarily appreciably so. If you were actually storing the selected element, as opposed to the value I'd see the benefit of `querySelectorAll`. – Jon P Jul 07 '17 at 03:45
  • @JonP - That *is* old school, but should be fine, yes. I guess what I've shown is a bit more generic, in that it works on elements not in a form, and can easily be adapted to work by class name or whatever. – nnnnnn Jul 07 '17 at 03:48
  • @nnnnnn Uncaught TypeError: Cannot read property 'addEventListener' of null. I am not sure why the code does not work when I use it in my file, but it works here on Stackoverflow. – Alex Ker Jul 07 '17 at 19:23
  • 1
    @AlexKer - That error means that `.getElementById()` couldn't find an element with the specified id. The script element should be placed *after* the elements it wants to access. Try putting it just before the closing `

    ` tag.

    – nnnnnn Jul 07 '17 at 22:02
  • @nnnnnn I placed the – Alex Ker Jul 09 '17 at 18:30
  • Sorry, I don't know what else to suggest. I can't reproduce that problem. – nnnnnn Jul 10 '17 at 02:15