2

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?

1 Answer 1

6

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:

  • Giving multiple elements the same id (e.g. if you have a radio button group where each member has to have the same name).
  • Giving one element a name and a different element a matching id

Do not use "ids" at all

If you don't give a form control an id, then you can't use a for attribute to associate it with a <label> element. Support for for attributes 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.

3
  • The opposite is also true. :) Jul 30, 2012 at 14:56
  • @Diodeus, the opposite of the whole answer? That's kinda hard to imagine. :)
    – bzlm
    Jul 30, 2012 at 15:00
  • @Quentin Yes, indeed I've modeled most of my dynamic html-generating functions to include specifications for <label>s (I hate when I have to click in a 5x5 pixel area :D), which as you correctly say would be useless without id. So I guess I'll stick to the old habits, specifying ids only when needed. Thank you for your valued opinion :)
    – Cranio
    Jul 30, 2012 at 15:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.