skip to Main Content

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


  1. If you are using native JavaScript without jQuery, you can query for the selected radio button with the :checked selector.

    function fun() {
      const { value } = document.querySelector('input[name="drone"]:checked');
      console.log(value);
    }
    .as-console-wrapper { max-height: 4.33rem !important; }
    <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>

    As for the serializeArray question, it is doing something like this:

    const serializeArray = (formItem) => {
      const
        container = formItem.closest('form') ?? document.body,
        name = formItem.name;
      let value;
      switch (formItem.tagName.toLowerCase()) {
        case 'select':
        case 'textarea':
          value = formItem.value;
          break;
        case 'input':
          switch (formItem.type) {
            case 'text':
              value = formItem.value;
              break;
            case 'checkbox':
            case 'radio':
              value = container.querySelector(`input[name="${name}"]:checked`).value;
              break;
          }
      }
      return [{ name, value }];
    }
    
    function fun() {
      const droneEl = document.querySelector('input[name="drone"]');
      const serialized = serializeArray(droneEl);
      console.log(serialized);
    }
    .as-console-wrapper { max-height: 6rem !important; }
    <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>

    The serialization usually occurs on the form, we can derive this information for all form elements via:

    const formAsJson = (form) =>
      (formData =>
        [...formData.keys()].reduce((result, key) => ({
          ...result,
          [key]: result[key] ? formData.getAll(key) : formData.get(key)
        }), {}))
      (new FormData(form));
    
    const serializeArray = (form) =>
      Object.entries(formAsJson(form))
        .flatMap(([name, value]) =>
          Array.isArray(value)
            ? value.map(item => ({ name, value: item }))
            : ({ name, value }));
    
    const fun = () => {
      const serialized = serializeArray(document.forms.settings);
    
      console.log(serialized);
    }
    <form name="settings">
      <fieldset>
        <legend>Select a maintenance drone:</legend>
        <div>
          <input type="radio" name="drone" value="huey" checked>
          <label for="huey">Huey</label>
        </div>
        <div>
          <input type="radio" name="drone" value="dewey">
          <label for="dewey">Dewey</label>
        </div>
        <div>
          <input type="radio" name="drone" value="louie">
          <label for="louie">Louie</label>
        </div>
      </fieldset>
      <fieldset>
        <legend>Select options:</legend>
        <div>
          <input type="checkbox" name="time" value="morning" checked>
          <label for="huey">Morning</label>
        </div>
        <div>
          <input type="checkbox" name="time" value="afternoon">
          <label for="dewey">Afternoon</label>
        </div>
        <div>
          <input type="checkbox" name="time" value="evening">
          <label for="louie">Evening</label>
        </div>
      </fieldset>
      <button type="button" onclick="fun()">Click Me</button>
    </form>
    Login or Signup to reply.
  2. 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:

    document.querySelector('input[name="drone"]:checked').value;
    
    Login or Signup to reply.
  3. use this I think it will help you:

    document.querySelector('input[name="drone"]:checked').value;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search