我知道当有多个时我可以使用 jQuery ( how to get multiple checkbox value using jquery ) 来获取复选框值,但是我的复选框输入在 html 表单中,所以那些 jQuery 解决方案不起作用,因为它们都没有获取复选框值从一个表单中。
我尝试从表单中提取值,但它只是创建了一个奇怪的单选节点列表,它似乎在计算复选框名称而不是值在文档中出现的次数。
function validateForm() {
var checks = document.forms["TestForm"]["ParticipantSelection[]"];
alert(checks);
}
<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>
但我不知道如何让 js 获取表单输入中的值而不是计算其他内容,也不知道如何访问选中框的值
最佳答案
您可以使用 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;
}
<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>
关于javascript - 如何从html表单中获取多个复选框的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43265149/