如果在表单提交时勾选复选框输入值数据,浏览器是否仅发送复选框输入值数据是标准行为?
如果没有提供值数据,默认值是否总是“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”。您可以使用隐藏输入,而不是捕获复选框值
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'),
输入类型="hidden" name="is_main" value="0"
输入类型="checkbox" name="is_main" value="1"
所以你可以像我在应用程序中那样控制。 如果检查成功,则发送值1,否则为0
我用下面的代码解决了这个问题:
HTML表单
<input type="checkbox" id="is-business" name="is-business" value="off" onclick="changeValueCheckbox(this)" >
<label for="is-business">Soy empresa</label>
而javascript函数通过改变复选框值的形式:
//change value of checkbox element
function changeValueCheckbox(element){
if(element.checked){
element.value='on';
}else{
element.value='off';
}
}
服务器检查数据张贴是“打开”还是“关闭”。我使用的是playframework java
final Map<String, String[]> data = request().body().asFormUrlEncoded();
if (data.get("is-business")[0].equals('on')) {
login.setType(new MasterValue(Login.BUSINESS_TYPE));
} else {
login.setType(new MasterValue(Login.USER_TYPE));
}
浏览器只发送复选框输入是标准行为吗 价值数据是否在表单提交时进行检查?
是的,因为否则就没有可靠的方法来确定复选框是否被选中(如果它改变了值,则可能存在这样的情况,即当您选中的期望值与它被交换到的值相同时)。
如果没有提供值数据,默认值是否总是“on”?
其他答案证实“开”是默认值。但是,如果你对值不感兴趣,可以使用:
if (isset($_POST['the_checkbox'])){
// name="the_checkbox" is checked
}