I am trying to find out where the state of the radio buttons is saved within the browser, in order to find the selected one.
I did some research and I did find out that by using jQuery and the serializeArray on the input
I can get the selected value.
Nevertheless, in the browser’s HTML when clicking on a radio button nothing visually changes. Which makes me think, that this is impossible with Vanilla JS?
I am quite confused by the browser’s behavior and in addition, I do not understand how the serializeArray
is working.
The documentation states
The .serializeArray() method uses the standard W3C rules for successful controls to determine which elements it should include;
So I guess this is a black box and some magic happens in there, to determine the selected checkbox?
function fun() {
const a = $('#fieldset').find('input')
const b = a.serializeArray()
console.log(b)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<fieldset id="fieldset">
<legend>Select a maintenance drone:</legend>
<div>
<input type="radio" id="huey" name="drone" value="huey"
checked>
<label for="huey">Huey</label>
</div>
<div>
<input type="radio" id="dewey" name="drone" value="dewey">
<label for="dewey">Dewey</label>
</div>
<div>
<input type="radio" id="louie" name="drone" value="louie">
<label for="louie">Louie</label>
</div>
</fieldset>
<button onclick="fun()">
click me
</button>
3
Answers
If you are using native JavaScript without jQuery, you can query for the selected radio button with the
:checked
selector.As for the
serializeArray
question, it is doing something like this:The serialization usually occurs on the form, we can derive this information for all form elements via:
Based on the top voted answer from How to get the selected radio button’s value?, you could use the following Vanilla JavaScript to retrieve the currently selected value from the radio button:
use this I think it will help you: