Frosted Cupcake
Frosted Cupcake

Reputation: 1970

How to access the value of checked radio box through javascript

I am rendering a HTML form through JS and when the user fills the data and clicks on submit, then I am converting into a JSON. But I am unable to fetch the value of checked radio box. Here's my code for rendering the radio box-

return '<div class="">\
        <label class="" for="">Gender</label>\
        <div class="">\
            <div id="">\
                <div class="">\
                    <label for="" class="radio">Male</label>\
                    <input id="" type="radio" name = "gender" value="M">\
                </div>\
                <div class="">\
                    <label for="" class="radio">Female</label>\
                    <input id="" type="radio" name = "gender" value="F">\
                </div>\
                <div class="">\
                    <label for="" class="radio">Others</label>\
                    <input id="" type="radio" name = "gender" value="O">\
                </div>\
            </div>\
        </div>\
    </div>';
};

Here's my function to convert user filled form to JSON,

var convertIntoJSON = function(elements) {
    return [].reduce.call(elements, function(data, element){
        data[element.name] = element.value;
        return data;
    }, {});
};

I am calling the above function, as convertIntoJSON(form.elements), where form is my actual form container.

Please tell me how can I access the checked radio button through this, through this code no matter what I select in gender field, I am getting gender as "O" everytime.

Upvotes: 0

Views: 55

Answers (1)

nvioli
nvioli

Reputation: 4219

As I said in my comment, you can't use this shorthand to get the value of a radio array. Here's a workaround that still supports your original function for non-radio inputs:

var convertIntoJSON = function(elements) {
    return [].reduce.call(elements, function(data, element){
        if (element.type === "radio") {
          if (element.checked) {
            data[element.name] = element.value;
          }
        } else {
            data[element.name] = element.value;
        }
        return data;
    }, {});
};

var logSelected = document.getElementById('logSelected');
var form = document.getElementById('theForm');

logSelected.addEventListener('click',() => {
  console.log(convertIntoJSON(form.elements));
})
<form id="theForm">
  <label for="" class="radio">Male</label>
  <input id="" type="radio" name = "gender" value="M">

  <label for="" class="radio">Female</label>
  <input id="" type="radio" name = "gender" value="F">

  <label for="" class="radio">Others</label>
  <input id="" type="radio" name = "gender" value="O">

</form>

<input type="button" value="log selected" id="logSelected"/>

Upvotes: 3

Related Questions