I’ve a long time habit when coding to name most of the fields in a HTML form with matching “name” and “id” attributes, when possible. This allows me to simplify dynamic HTML generation, f. ex. creating a dropdown in PHP with:
select("myselect", $values);
instead of:
select("myselect", "myselectId", $values)
making also my element immediately available for selectors like those in JQuery (for validation etc.).
I know this solution has some issues (it is not good for radio buttons and checkboxes arrays – and for that I include an $id parameter in my PHP functions for radios -, it mixes two attributes meant for different purposes, it may cause problems when more than one form is on the page).
Is this bad habit really that bad? Have I overlooked some other possible negative side-effects?
What would you do in my place?
- Stick to this whenever it’s not causing any problem
- Do not use “ids” at all and use appropriate selectors for JQuery, like
$(form[name='...'] input[name='...']).somefunction() - Code in every single element a different id?
Giving an element matching names and ids does not cause a problem, so you don’t need to worry about it and it is not bad practise.
Related things that do cause problems:
If you don’t give a form control an id, then you can’t use a
forattribute to associate it with a<label>element. Support forforattributes is slightly better then for making the form control a descendent of the label. Since labels are really useful for accessibility (they increase the size of the click target and give a non-visual association between the control and the input) leaving ids off is not a good idea.