js匹配多选框选中项

 复选框

<!doctype html>
<html>
<head>
  <meta charset="gb2312">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>复选框多选</title>
</head>

<body>
  <div>
    <input type="checkbox"  value="1"/><span>红色</span>
    <input type="checkbox"  value="2"/><span>绿色</span>
    <input type="checkbox"  value="3"/><span>黄色</span>
    <input type="checkbox"  value="4"/><span>蓝色</span>
    <input type="checkbox"  value="5"/><span>紫色</span>
  </div>

  <div>
    <button type="button" onclick="getValue()">获取选中的复选框的值</button>
  </div>

  <div>
   <p id="show"></p>
  </div>

  <script>

    function getValue()
    {
      //获取所有的input标签
      var input = document.getElementsByTagName("input");
      var str="选中的值为:";
      for (var i = 0; i < input.length; i++)
      {
        var obj = input[i];
        //判断是否是checkbox并且已经选中
        if (obj.type == "checkbox" && obj.checked) 
        {
          var code = obj.value;//获取checkbox的值
          str=str+code+",";
        }
      }
     document.getElementById("show").innerText=str;
    }
  </script>

</body>
</html>
原文地址:https://www.cnblogs.com/wn798/p/11988043.html