可以具有相同“名称"的输入属性 [英] Input attributes that can have the same "name"
问题描述
我注意到,如果您有几个收音机,您需要使所有收音机的 name 属性相同,以便收音机按预期工作:
I noticed that if you have a couple of radios together, you are required to make the name attribute identical on all of them in order for the radios to work as expected:
<label for="a1"><input type="radio" name="a" id="a1" value="1">1</label>
<label for="a2"><input type="radio" name="a" id="a2" value="2">2</label>
<label for="a3"><input type="radio" name="a" id="a3" value="3">3</label>
<label for="a4"><input type="radio" name="a" id="a4" value="4">4</label>
单选输入是否是唯一可以具有重复名称属性的输入类型(并且必须这样做)?如果我对任何其他输入执行此操作,浏览器会认为它无效,对吗?
Is the radio input the only input type where you can have duplicate name attributes (and required to do so)? If I do this on any other input, it would be considered invalid by the browser, right?
我之所以这么问是因为我需要在脚本中处理这种情况,并且想知道在处理多个相同名称时是否还应该考虑其他输入类型.
I'm asking this because I need to handle this situation in a script, and want to know if there are other input types I should take into consideration when dealing with multiple identical names.
推荐答案
从用户交互的角度来看,input:radio
元素使用相同的 [name]
以便浏览器知道一次只允许一个:checked
.
From a user-interaction perspective, input:radio
elements use the same [name]
so that the browser knows to only allow one to be :checked
at a time.
从表单提交的角度来看,任何元素都可以具有相同的名称,它们都将被序列化为HTML 规范
From a form-submission perspective, any elements can have the same name, they will all be serialized into the query string as defined in the HTML Spec
这里有几个例子:
<form action="/foo/bar">
<input type="hidden" name="fizz" value="buzz" />
<input type="radio" name="foo" value="bar" />
<input type="radio" name="foo" value="baz" />
<input type="submit" value="Go" />
</form>
提交此表单(选中 bar
单选按钮)将导致查询字符串:
Submitting this form (with the bar
radio button checked) will result in a query string of:
?fizz=buzz&foo=bar
但是,如果您将 input:hidden
元素的名称更改为 foo
:
However, if you change the name of the input:hidden
element to foo
:
<form action="/foo/bar">
<input type="hidden" name="foo" value="buzz" />
<input type="radio" name="foo" value="bar" />
<input type="radio" name="foo" value="baz" />
<input type="submit" value="Go" />
</form>
查询字符串将是:
?foo=buzz&foo=bar
服务器应该正确解析这个,这样你就可以得到 buzz
和 bar
值,但是我发现一些服务器 -辅助语言在查询字符串解析方面有一些怪癖.
The server should correctly parse this so that you can get both buzz
and bar
values, however I've found that some server-side languages have quirks when it comes to query string parsing.
如果键以 []
为后缀,PHP 尤其会将键转换为数组:
PHP in particular will turn keys into arrays if the key is suffixed with []
:
?foo[]=buzz&foo[]=bar
将有 $_GET['foo'] = array('buzz', 'bar');
这篇关于可以具有相同“名称"的输入属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!