javascript 使用jQuery获取表单提交的复选框值并存储在变量中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11515743/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get checkbox value on form submit and store in a variable using jQuery
提问by Chris
Have a form using multiple checkboxes with a class of 'test' (only one of which can be checked however similar to using radio buttons - not my idea btw!).
有一个使用多个复选框的表单和一类“测试”(只能检查其中一个,但类似于使用单选按钮 - 顺便说一句,不是我的想法!)。
When the form is submitted I want to get the value of the checkbox that is checked and store it in a variable - can anyone help here?
提交表单后,我想获取选中的复选框的值并将其存储在变量中 - 任何人都可以在这里提供帮助吗?
Cheers!
干杯!
Chris
克里斯
回答by nnnnnn
$("form").submit(function() {
var aVariable = $('input.test[type="checkbox"]:checked', this).val();
});
.val()
returns undefined
if called on an empty jQuery object, which would be the case here if no checkboxes are checked.
.val()
undefined
如果在空的 jQuery 对象上调用,则返回,如果没有选中复选框,则会出现这种情况。
回答by gaurang171
Please try below solution on codebins:
请在代码箱上尝试以下解决方案:
Note: Add latest jquery.js javascript file on header tag first.
注意:首先在 header 标签上添加最新的 jquery.js javascript 文件。
HTML:
HTML:
<form id="frm1" method="post">
<input type="radio" class="test" checked="checked" value="radio1">
Radio1
<input type="radio" class="test" checked="checked" value="radio2">
Radio2
<input type="radio" class="test" value="radio3">
Radio3
<br/>
<input type="checkbox" class="test" checked="checked" value="check1">
Check1
<input type="checkbox" class="test" value="check2">
Check2
<input type="checkbox" class="test" checked="checked" value="check3">
Check3
<br/>
<input type="submit" value="submit" />
</form>
jQuery within Script tag:
Script 标签中的 jQuery:
$(function() {
$("#frm1").submit(function() {
$("input.test[type=checkbox]:checked").each(function() {
alert($(this).val());
});
return false;
});
});
I have done above bin on http://codebins.com/bin/4ldqpap
我已经在http://codebins.com/bin/4ldqpap上完成了上面的 bin
回答by sankar dey
this will work
这会起作用
$(function() {
$("#frm1").submit(function() {
$("input.test[type=checkbox]:checked").each(function() {
alert($(this).val());
});
return false;
});
});
回答by Patel Sunil
var inputElements = document.getElementsByClassName('messageCheckbox');
var checkedValue=[];
for(var i=0; inputElements[i]; ++i){
console.log(inputElements[i]);
if(inputElements[i].checked){
checkedValue.push(inputElements[i].value);
}
}
alert(checkedValue)