JS 如何获取radio或者checkbox选中后的值

效果图

废话不多说,直接上代码:

代码:


<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>JS 如何获取radio或者checkbox选中后的值</title>
</head>

<body>
  <p>单选框</p>
  <input type="radio" name="sex" value="man" id="man" checked onclick="inputChecked()">
  <label for="man">男</label>
  <input type="radio" name="sex" value="female" id="female" onclick="inputChecked()">
  <label for="female">女</label>
  <p>多选框</p>
  <input type="checkbox" name="fruits" value="apple" id="apple" checked onclick="inputChecked()">
  <label for="apple">苹果</label>
  <input type="checkbox" name="fruits" value="orange" id="orange" onclick="inputChecked()">
  <label for="orange">橙子</label>
  <script>
    inputChecked();

    function inputChecked() {
      var inputSelect = document.getElementsByTagName('input');
      var obj = {
          radio: [],
          checkbox: []
        },
        value = '';
      for (var i = 0, len = inputSelect.length; i < len; i++) {
        if (inputSelect[i].checked && inputSelect[i].type === 'radio') {
          obj.radio.push(inputSelect[i].value);
          value += '单选框:' + inputSelect[i].value + '\n';
        }
        if (inputSelect[i].checked && inputSelect[i].type === 'checkbox') {
          obj.checkbox.push(inputSelect[i].value);
          value += '多选框:' + inputSelect[i].value + '\n';
        }
      }
      alert(value);
      return obj;
    }
  </script>
</body>

</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。