如果在表单提交时勾选复选框输入值数据,浏览器是否仅发送复选框输入值数据是标准行为?
如果没有提供值数据,默认值是否总是“on”?
假设上述假设是正确的,那么所有浏览器的这种行为是否一致呢?
如果在表单提交时勾选复选框输入值数据,浏览器是否仅发送复选框输入值数据是标准行为?
如果没有提供值数据,默认值是否总是“on”?
假设上述假设是正确的,那么所有浏览器的这种行为是否一致呢?
当前回答
Just like ASP.NET variant, except put the hidden input with the same name before the actual checkbox (of the same name). Only last values will be sent. This way if a box is checked then its name and value "on" is sent, whereas if it's unchecked then the name of the corresponding hidden input and whatever value you might like to give it will be sent. In the end you will get the $_POST array to read, with all checked and unchecked elements in it, "on" and "false" values, no duplicate keys. Easy to process in PHP.
其他回答
浏览器只发送复选框输入是标准行为吗 价值数据是否在表单提交时进行检查?
是的,因为否则就没有可靠的方法来确定复选框是否被选中(如果它改变了值,则可能存在这样的情况,即当您选中的期望值与它被交换到的值相同时)。
如果没有提供值数据,默认值是否总是“on”?
其他答案证实“开”是默认值。但是,如果你对值不感兴趣,可以使用:
if (isset($_POST['the_checkbox'])){
// name="the_checkbox" is checked
}
是的,标准行为是仅在选中复选框时才发送值。这通常意味着您需要有一种方法来记住您期望在服务器端出现哪些复选框,因为并非所有数据都是从表单返回的。
默认值总是“on”,这应该在不同浏览器中保持一致。
这在W3C HTML 4推荐中包含:
复选框(和单选按钮)是可以切换的开/关开关 由用户决定。当控制元件被检查时,开关是“打开”的 属性已设置。当提交表单时,只有“on”复选框 控制可以成功。
输入类型="hidden" name="is_main" value="0"
输入类型="checkbox" name="is_main" value="1"
所以你可以像我在应用程序中那样控制。 如果检查成功,则发送值1,否则为0
当且仅当复选框被选中时,复选框将发布值“on”。您可以使用隐藏输入,而不是捕获复选框值
JS:
var chk = $('input[type="checkbox"]');
chk.each(function(){
var v = $(this).attr('checked') == 'checked'?1:0;
$(this).after('<input type="hidden" name="'+$(this).attr('rel')+'" value="'+v+'" />');
});
chk.change(function(){
var v = $(this).is(':checked')?1:0;
$(this).next('input[type="hidden"]').val(v);
});
HTML:
<label>Active</label><input rel="active" type="checkbox" />
在你的帖子中
'your_field': your_field.is(':checked'),