在 jQuery 中序列化复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5389050/
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
serializing checkboxes in jQuery
提问by user670874
I have a jQuery form in which I create a series of checkboxes:
我有一个 jQuery 表单,我在其中创建了一系列复选框:
<?php
<form method="post" id="b-form" action="../createb.php">
for ($i=0; $i<$request_count; $i++){
<div class="request-check">
<table>
<tr>
<td><input type="checkbox" name="show_request[]" value="request".$i." checked="checked"/>select request</td>
</tr>
</table>
</div>
}
javascript
javascript
$.ajax({
type: 'POST',
url: '../createb.php',
data: $('#b-form').serialize(),
success: function (msg){
alert(msg);
}
})
at the moment createb.php is just testing the form
目前 createb.php 只是测试表单
$requests = $_POST['show_request'];
$request_count = count($requests);
echo 'count: '.$request_count;
echo $requests[0];
The Problem is that the serialize function only sees the first checkbox and indicates whether it has been checked or not. It does not see any of the other check boxes. Does anybody have an idea why the other check boxes do not get serialized and what to do about it?
问题是序列化函数只看到第一个复选框并指示它是否已被选中。它看不到任何其他复选框。有没有人知道为什么其他复选框没有被序列化以及如何处理?
Thanks David
谢谢大卫
回答by balexandre
Well, that's true as you are having all checkboxes with the name name
and any id
to separate them.
嗯,这是真的,因为您拥有所有带有名称的复选框,name
并且id
可以将它们分开。
try to create them like:
尝试创建它们,如:
<input
type = "checkbox"
id = "ckb_<?php echo $i ?>"
name = "ckb_<?php echo $i ?>_show_request[]"
value = "request".$i."
checked = "checked"/> select request
I'm sure that $('#b-form').serialize()
will now generate all checkboxes as you want them
我确定$('#b-form').serialize()
现在会根据需要生成所有复选框
回答by user3832931
Quote from Jquery documentation: Only "successful controls" are serialized to the string (when using $(form).serialize()) or to array($(form).serializeArray()). Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked.
引用Jquery 文档:只有“成功的控件”被序列化为字符串(使用 $(form).serialize() 时)或数组($(form).serializeArray())。来自复选框和单选按钮(“radio”或“checkbox”类型的输入)的值仅在被选中时才包含在内。
You can use something like this to emulate behavior similar to what you expect:
您可以使用这样的东西来模拟与您期望的行为类似的行为:
var myCbValuesArray = $("input:checkbox").map(function(){
return $(this).is(":checked");
}).get();
回答by JulienB
Your selector is wrong.
你的选择器是错误的。
Try :
尝试 :
$('#b-form input:checkbox').serialize()
For get only checked input, use :
对于仅获取检查输入,请使用:
$('#b-form input:checkbox:checked').serialize()
回答by Ravi Hirani
This will work for you.
这对你有用。
You can get selected checkboxes values by
您可以通过以下方式获取选定的复选框值
$("input[type='checkbox']:checked").serialize();