Html 复选框输入是否仅在选中时发布数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11424037/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:34:46  来源:igfitidea点击:

Do checkbox inputs only post data if they're checked?

htmlinputcheckbox

提问by Mark

Is it standard behaviour for browsers to only send the checkbox input value data if it is checked upon form submission?

如果在表单提交时选中它,浏览器是否仅发送复选框输入值数据的标准行为?

And if no value data is supplied, is the default value always "on"?

如果没有提供值数据,默认值是否总是“开启”?

Assuming the above is correct, is this consistent behaviour across all browsers?

假设以上是正确的,所有浏览器的这种行为是否一致?

回答by John C

Yes, standard behaviour is the value is only sent if the checkbox is checked. This typically means you need to have a way of remembering what checkboxes you are expecting on the server side since not all the data comes back from the form.

是的,标准行为是仅在选中复选框时才发送值。这通常意味着您需要有一种方法来记住服务器端期望的复选框,因为并非所有数据都从表单返回。

The default value is always "on", this should be consistent across browsers.

默认值始终为“on”,这在浏览器之间应该是一致的。

This is covered in the W3C HTML 4 recommendation:

W3C HTML 4 建议中涵盖了这一点:

Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.

复选框(和单选按钮)是可以由用户切换的开/关开关。当设置了控件元素的检查属性时,开关处于“打开”状态。提交表单时,只有“on”复选框控件才能成功。

回答by Dai

In HTML, each <input />element is associated with a single (but not unique) name and value pair. This pair is sent in the subsequent request (in this case, a POST request body) only if the <input />is "successful".

在 HTML 中,每个<input />元素都与一个(但不是唯一的)名称和值对相关联。仅当<input />“成功”时,才会在后续请求(在本例中为 POST 请求正文)中发送该对。

So if you have these inputs in your <form>DOM:

因此,如果您的<form>DOM 中有这些输入:

<input type="text"     name="one"   value="foo"                        />
<input type="text"     name="two"   value="bar"    disabled="disabled" />
<input type="text"     name="three" value="first"                      />
<input type="text"     name="three" value="second"                     />

<input type="checkbox" name="four"  value="baz"                        />
<input type="checkbox" name="five"  value="baz"    checked="checked"   />
<input type="checkbox" name="six"   value="qux"    checked="checked" disabled="disabled" />
<input type="checkbox" name=""      value="seven"  checked="checked"   />

<input type="radio"    name="eight" value="corge"                      />
<input type="radio"    name="eight" value="grault" checked="checked"   />
<input type="radio"    name="eight" value="garply"                     />

Will generate these name+value pairs which will be submitted to the server:

将生成这些将提交给服务器的名称+值对:

one=foo
three=first
three=second
five=baz
eight=grault

Notice that:

请注意:

  • twoand sixwere excluded because they had the disabledattribute set.
  • threewas sent twice because it had two valid inputs with the same name.
  • fourwas not sent because it is a checkboxthat was not checked
  • sixwas not sent despite being checkedbecause the disabledattribute has a higher precedence.
  • sevendoes not have a name=""attribute sent, so it is not submitted.
  • twosix被排除,因为他们的disabled属性集。
  • three被发送两次,因为它有两个同名的有效输入。
  • four没有被发送,因为它checkbox不是checked
  • six尽管存在checked,但并未发送,因为该disabled属性具有更高的优先级。
  • seven没有name=""发送属性,所以没有提交。

With respect to your question: you can see that a checkbox that is not checked will therefore not have its name+value pair sent to the server - but other inputs that share the same name will be sent with it.

关于您的问题:您可以看到未选中的复选框因此不会将其名称+值对发送到服务器 - 但共享相同名称的其他输入将与其一起发送。

Frameworks like ASP.NET MVC work around this by (surreptitiously) pairing every checkboxinput with a hiddeninput in the rendered HTML, like so:

像 ASP.NET MVC 这样的框架通过(秘密地)将每个checkbox输入与hidden呈现的 HTML 中的输入配对来解决这个问题,如下所示:

@Html.CheckBoxFor( m => m.SomeBooleanProperty )

Renders:

渲染:

<input type="checkbox" name="SomeBooleanProperty" value="true" />
<input type="hidden"   name="SomeBooleanProperty" value="false" />

If the user does not check the checkbox, then the following will be sent to the server:

如果用户没有选中该复选框,则以下内容将发送到服务器:

SomeBooleanProperty=false

If the user does check the checkbox, then both will be sent:

如果用户确实选中了复选框,则两者都将被发送:

SomeBooleanProperty=true
SomeBooleanProperty=false

But the server will ignore the =falseversion because it sees the =trueversion, and so if it does not see =trueit can determine that the checkbox was rendered and that the user did not check it - as opposed to the SomeBooleanPropertyinputs not being rendered at all.

但是服务器将忽略=false版本,因为它看到了=true版本,因此如果它没有看到=true它可以确定复选框已呈现并且用户没有选中它 - 与SomeBooleanProperty根本没有呈现输入相反。

回答by Adam Zalcman

If checkbox isn't checked then it doesn't contribute to the data sent on form submission.

如果未选中复选框,则它不会影响表单提交时发送的数据。

HTML5 section 4.10.22.4 Constructing the form data setdescribes the way form data is constructed:

HTML5 第4.10.22.4构建表单数据集描述了表单数据的构建方式:

If any of the following conditions are met, then skip these substeps for this element: [...]

The field element is an input element whose type attribute is in the Checkbox state and whose checkedness is false.

如果满足以下任何条件,则跳过此元素的这些子步骤:[...]

field元素是一个input元素,其type属性为Checkbox状态,checkness为false。

and then the default valued onis specified if valueis missing:

on如果value缺少,则指定默认值:

Otherwise, if the field element is an input element whose type attribute is in the Checkbox state or the Radio Button state, then run these further nested substeps:

If the field element has a value attribute specified, then let value be the value of that attribute; otherwise, let value be the string "on".

否则,如果 field 元素是一个 input 元素,其 type 属性处于 Checkbox 状态或 Radio Button 状态,则运行这些进一步的嵌套子步骤:

如果 field 元素指定了 value 属性,则让 value 为该属性的值;否则,让 value 为字符串“on”。

Thus unchecked checkboxes are skipped during form data construction.

因此,在表单数据构建期间会跳过未选中的复选框。

Similar behavior is required under HTML4. It's reasonable to expect this behavior from all compliant browsers.

HTML4下需要类似的行为。期待所有兼容浏览器的这种行为是合理的。

回答by Lanister

Checkboxes are posting value 'on' if and only if the checkbox is checked. Insted of catching checkbox value you can use hidden inputs

当且仅当复选框被选中时,复选框才会发布值“on”。Insted 捕获复选框值,您可以使用隐藏输入

JS:

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:

HTML:

<label>Active</label><input rel="active" type="checkbox" />

回答by Jay

Is it standard behaviour for browsers to only send the checkbox input value data if it is checked upon form submission?

如果在表单提交时选中它,浏览器是否仅发送复选框输入值数据的标准行为?

Yes, because otherwise there'd be no solid way of determining if the checkbox was actually checked or not (if it changed the value, the case may exist when your desired value if it were checked would be the same as the one that it was swapped to).

是的,因为否则将没有可靠的方法来确定复选框是否被实际选中(如果它更改了值,则可能存在这种情况,如果选中它,您想要的值将与它相同交换为)。

And if no value data is supplied, is the default value always "on"?

如果没有提供值数据,默认值是否总是“开启”?

Other answers confirm that "on" is the default. However, if you are not interested in the value, just use:

其他答案确认“开”是默认值。但是,如果您对该值不感兴趣,只需使用:

if (isset($_POST['the_checkbox'])){
    // name="the_checkbox" is checked
}

回答by Alex W

From HTML 4 spec, which should be consistent across almost all browsers:

来自 HTML 4 规范,它应该在几乎所有浏览器中保持一致:

http://www.w3.org/TR/html401/interact/forms.html#checkbox

http://www.w3.org/TR/html401/interact/forms.html#checkbox

Checkboxes (and radio buttons) are on/off switches that may be toggled by the user. A switch is "on" when the control element's checked attribute is set. When a form is submitted, only "on" checkbox controls can become successful.

复选框(和单选按钮)是可以由用户切换的开/关开关。当设置了控件元素的检查属性时,开关处于“打开”状态。提交表单时,只有“on”复选框控件才能成功。

Successful is defined as follows:

成功定义如下:

A successful control is "valid" for submission. Every successful control has its control name paired with its current value as part of the submitted form data set. A successful control must be defined within a FORM element and must have a control name.

一个成功的控制是“有效的”提交。每个成功的控件都将其控件名称与其当前值配对,作为提交的表单数据集的一部分。成功的控件必须在 FORM 元素中定义并且必须具有控件名称。

回答by Muhammad Amir Shahzad

input type="hidden" name="is_main" value="0"

输入类型=“隐藏”名称=“is_main”值=“0”

input type="checkbox" name="is_main" value="1"

输入类型=“复选框”名称=“is_main”值=“1”

so you can control like this as I did in the application. if it checks then send value 1 otherwise 0

所以你可以像我在应用程序中那样控制。如果它检查然后发送值 1 否则 0

回答by Cobolt

None of the above answers satisfied me. I found the best solution is to include a hidden input beforeeach checkbox input with the same name.

以上答案都没有让我满意。我发现最好的解决方案是每个具有相同名称的复选框输入之前包含一个隐藏输入。

<input type="hidden" name="foo[]" value="off"/>

<input type="hidden" name="foo[]" value="off"/>

<input type="checkbox" name="foo[]"/>

<input type="checkbox" name="foo[]"/>

Then on the server side, using a little algorithm you can get something more like HTML should provide.

然后在服务器端,使用一个小算法,你可以得到更像 HTML 应该提供的东西。

function checkboxHack(array $checkbox_input): array
{
    $foo = [];
    foreach($checkbox_input as $value) {
        if($value === 'on') {
            array_pop($foo);
        }
        $foo[] = $value;
    }
    return $foo;
}

This will be the raw input

这将是原始输入

array (
    0 => 'off',
    1 => 'on',
    2 => 'off',
    3 => 'off',
    4 => 'on',
    5 => 'off',
    6 => 'on',
),

And the function will return

该函数将返回

array (
    0 => 'on',
    1 => 'off',
    2 => 'on',
    3 => 'on',
)  

回答by Alexander

I have a page (form) that dynamically generates checkbox so these answers have been a great help. My solution is very similar to many here but I can't help thinking it is easier to implement.

我有一个动态生成复选框的页面(表单),因此这些答案非常有帮助。我的解决方案与这里的许多解决方案非常相似,但我不禁认为它更容易实现。

First I put a hidden input box in line with my checkbox , i.e.

首先,我将一个隐藏的输入框与我的复选框一致,即

 <td><input class = "chkhide" type="hidden" name="delete_milestone[]" value="off"/><input type="checkbox" name="delete_milestone[]"   class="chk_milestone" ></td>

Now if all the checkboxesare un-selected then values returned by the hidden field will all be off.

现在,如果所有checkboxes都未选中,则隐藏字段返回的值将全部关闭。

For example, here with five dynamically inserted checkboxes, the form POSTSthe following values:

例如,这里有五个动态插入的复选框,形成POSTS以下值:

  'delete_milestone' => 
array (size=7)
  0 => string 'off' (length=3)
  1 => string 'off' (length=3)
  2 => string 'off' (length=3)
  3 => string 'on' (length=2)
  4 => string 'off' (length=3)
  5 => string 'on' (length=2)
  6 => string 'off' (length=3)

This shows that only the 3rd and 4th checkboxes are onor checked.

这表明只有第 3 个和第 4 个复选框是 onchecked

In essence the dummy or hidden input field just indicates that everything is off unless there is an "on"below the off index, which then gives you the index you need without a single line of client side code.

本质上,虚拟或隐藏输入字段仅表示一切都关闭,除非关闭索引下方有一个“打开”,然后它为您提供所需的索引,而无需一行客户端代码。

.

.

回答by Maugo

Having the same problem with unchecked checkboxes that will not be send on forms submit, I came out with a another solution than mirror the checkbox items.

对于不会在表单提交时发送的未选中复选框也有同样的问题,我提出了另一种解决方案,而不是镜像复选框项目。

Getting all unchecked checkboxes with

获取所有未选中的复选框

var checkboxQueryString;

$form.find ("input[type=\"checkbox\"]:not( \":checked\")" ).each(function( i, e ) {
  checkboxQueryString += "&" + $( e ).attr( "name" ) + "=N"
});