Best Way To Get All Selected Radio Button Values On Form Submission

In my web app, I have a form with a bunch of bootstrap panels. In each panel I have 3 radio buttons and each radio button has a unique id but shares the same name with the other 2 radio buttons in the panel.

I would like to save all of the values of all the selected radio buttons in an array but there is a couple problems. If I decide to store the value of a selected radio button in an array as soon as the radio button is selected, I will face an issue if the user changes his mind and selects a different radio button in the same panel.

If that happens I will have to go into the array and replace the value that was added previously with the new value. Also everything is generated dynamically so the number of panels, the radio button ids, radio button names, etc. are not known ahead of time.

Is there a way to get all the values of all the selected radio buttons and save them in the array only when the form submit button is clicked using jQuery or raw Javascript?

Hi @oangodd, you may try using the native javascript document.forms API like so:

var radioValue = document.forms['my-form-id']['my-radios-field-name'].value

That will give you the correct and currently selected value for your radio group.
Hope it helps…

Thanks for your reply but it is not at all what I was looking for. Please thoroughly read my post.

You can get all checked radios via the :checked pseudo class, and then map them to an array of their values like so:

const checkedRadios = document.querySelectorAll('input[type="radio"]:checked')
const values = Array.from(checkedRadios, radio => radio.value)

You could add an event listener to the event ‘submit’ and place all your code there.

This is exactly what I was looking for thank so much for your help.

1 Like

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