简体   繁体   中英

Two separate forms, with inputs that have same name and id

I have two forms on the same page with two labels with for attributes pointing to two checkboxes that have the same ID and name.

When I click one of the second form labels it checks the first form checkbox.

In this case the problem lies when you click the 'x name 2' label, it checks the 'x name' check box, even though they are in different forms:

 .customCheckbox div label { padding: 5px; background-color: white; border: 2px solid #aaaaaa; background-image: none; } .customCheckbox div input { margin: 8px auto; padding: 5px; text-align: left; margin-left: -999999px; float: left; } .customCheckbox input[type=checkbox]:checked ~ label, .customCheckbox input[type=radio]:checked ~ label { background-color: #117399; color: #eeeeee; } .customCheckbox input[type=radio]:checked ~ label { background-color: #117399; color: #eeeeee; } 
 <form style="margin:30px;"> <div class="customCheckbox"> <div> <input id="x" name="x" type="checkbox"/><label for="x">x name</label> </div> <br/> <div> <input id="y" name="y" type="checkbox"/> <label for="y">y name</label> </div> </div> </form> <form style="margin:30px;"> <div class="customCheckbox"> <div> <input id="x" name="x" type="checkbox"/><label for="x">x name 2</label> </div> <br/> <div> <input id="y" name="y" type="checkbox"/> <label for="y">y name 2</label> </div> </div> </form> 

  • I'd like to stay away from renaming the elements (as there are quite a few places this occurs)
  • I'd like to try to stay away from JavaScript (if possible)
  • Since I am using CSS for styling the labels and checkboxes I cannot nest the checkbox inside the label (because you can't style a parent element in CSS)

It is not legal to use the same id property twice on the same page. It does not matter at all if the elements are on the same form or different forms.

They can absolutely have the same name property. Names are what gets sent to your server. You can have fifty elements on the same form with the same name if you want.

But the whole purpose of IDs is that they absolutely must be unique on the page.

So simply make the first one ... id="x1" name="x" ... and the second ... id="x2" name="x" ... and then make your labels point to for="x1" or for="x2"

There's no problem when different input fields have the same name, as long as they're in a different form or they represent the same parameter (eg. in the case of radio buttons).

However, you should NEVER use the same id for different HTML elements.

From the HTML5 specs :

The id attribute specifies its element's unique identifier (ID) .

If you make your ids unique, your labels will work as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM