Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

javascript - Input attributes that can have the same "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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

Here are a couple examples:

<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>

Submitting this form (with the bar radio button checked) will result in a query string of:

?fizz=buzz&foo=bar

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>

The querystring will be:

?foo=buzz&foo=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 in particular will turn keys into arrays if the key is suffixed with []:

?foo[]=buzz&foo[]=bar will have $_GET['foo'] = array('buzz', 'bar');


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...