Input attributes that can have the same “name”

2019-01-25 08:37发布

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.

7条回答
再贱就再见
2楼-- · 2019-01-25 09:16

Is the radio input the only input type where you can have duplicate name attributes

No. Any form control can share a name with any other form control.

This is particularly useful for checkboxes (it allows you to say "Pick any number of these" and then loop over the results on the server without having to hard code a different name for each item.) and submit buttons (it lets you tell which one was clicked without looping over all possible names).

(and required to do so)?

Yes. Only radio buttons get special behaviour based on shared names.

查看更多
登录 后发表回答