如何从html表单中获取多个复选框值

S F*_*oyd 1 html javascript forms checkbox nodelist

我知道我可以使用 jQuery(如何使用 jquery 获取多个复选框值来获取多个复选框值,但是我的复选框输入在 html 表单中,所以那些 jQuery 解决方案不起作用,因为它们都没有得到表单中的复选框值。

我尝试从表单中提取值,但它只是创建了一个奇怪的无线电节点列表,它似乎计算复选框名称出现在文档中的次数而不是值。

function validateForm() {
  var checks = document.forms["TestForm"]["ParticipantSelection[]"];
  alert(checks);

}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>

<form name="TestForm" action="Video1.php" method="post" onsubmit="return validateForm()">

  <table>

    <tr>
      <th><img name="<?php echo $valueindicator[0];?>" src="<?php echo $all_four_images[0];?>" height="100">
      </th>

      <th><img name="<?php echo $valueindicator[1];?>" src="<?php echo $all_four_images[1];?>" height="100">
      </th>
      <th><img name="<?php echo $valueindicator[2];?>" src="<?php echo $all_four_images[2];?>" height="100">
      </th>
    </tr>

    <tr>
      <th> <input type="checkbox" name="ParticipantSelection[]" value="image1">
      </th>

      <th><input type="checkbox" name="ParticipantSelection[]" value="image2">
      </th>

      <th><input type="checkbox" name="ParticipantSelection[]" value="image3">
      </th>
    </tr>


  </table>
  <input type="hidden" name="AnswerCondition" value="BrowserCheckAnswer">


  <button type="submit">Continue</button>

</form>
Run Code Online (Sandbox Code Playgroud)

但我不知道如何让 js 获取表单输入中内容的值而不是计算其他内容,也不知道如何访问复选框的值

Mah*_*han 7

您可以使用jQuery .map()函数遍历每个检查的checkbox输入类型。这将返回一个带有selected复选框的对象。现在,要从jQuery对象获取数组,我们可以使用如下.get()方法:

尝试这个:

var validateForm = function() {
  var checks = $('input[type="checkbox"]:checked').map(function() {
    return $(this).val();
  }).get()
  console.log(checks);
  return false;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="TestForm" action="Video1.php" method="post" onsubmit="return validateForm()">
  <table>
    <tr>
      <th> <input type="checkbox" name="ParticipantSelection[]" value="image1">
      </th>

      <th><input type="checkbox" name="ParticipantSelection[]" value="image2">
      </th>

      <th><input type="checkbox" name="ParticipantSelection[]" value="image3">
      </th>
    </tr>
  </table>
  <input type="hidden" name="AnswerCondition" value="BrowserCheckAnswer"/>
  <button type="submit">Continue</button>
</form>
Run Code Online (Sandbox Code Playgroud)