如何通过javascript访问已检查的单选框的值

时间:2018-02-02 18:19:57

标签: javascript jquery html json forms

我通过JS呈现HTML表单,当用户填写数据并点击提交时,我转换为JSON。但我无法获取已检查单选框的值。这是我渲染收音机盒的代码 -

cascading LOV parent item(s)

这是我将用户填写的表单转换为JSON的函数,

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>';
};

我正在调用上面的函数,如var convertIntoJSON = function(elements) { return [].reduce.call(elements, function(data, element){ data[element.name] = element.value; return data; }, {}); }; ,其中form是我的实际表单容器。

请告诉我如何通过此代码访问选中的单选按钮,无论我在性别字段中选择什么,我每次都会将性别标记为“O”。

1 个答案:

答案 0 :(得分:3)

正如我在评论中所说,你不能用这个简写来获得无线电阵列的价值。这是一个仍然支持非无线电输入原始功能的解决方法:

&#13;
&#13;
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));
})
&#13;
<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"/>
&#13;
&#13;
&#13;