htmlformsinputnamespacesserver-side-scripting

Is there a way to give HTML inputs some sort of namespace to avoid collisions?


<!-- Some place on the webpage -->
  <input type="text" id="firstName">

<!-- Some other place on the same webpage, or maybe content ajaxed in later -->
  <input type="text" id="firstName">

Let's say I have a server-side script that generates an HTML page with some input fields each with its own ID. One server-side class may be responsible for adding input fields to one part of the webpage while another class handles another part of the webpage. Or you might have different programmers working on different parts of the page. I want to avoid collision with the HTML input field IDs. An example of this could be a parent form that has a jQuery dialog popup with input field IDs the same as the parent. Currently, I am prefixing the IDs with the name of the server-side class that generates them (and an underscore to make it clear which part is the prefix). To get a fully unique ID this way, I might have to start including the full namespace of the server-side class, and this might make my IDs very long.

Is there a better approach than prefixing the inputs or what is the best practice for this? I normally use camelCase for all my variables, with only this exception. Is this a good exception for breaking that rule?

What are most of you doing? Are you altering the way you select these input fields instead of by ID? Wrapping the input fields in form tags or div tags and adding functionality to the server-side to create these? (I'd like to have the freedom of not restricting what I wrap these inputs in to select them. My server-side code should just generate client-side code that grabs the values only knowing those inputs are going onto the page, and not knowing about any other tags on the page. Much easier to manage.) Are you adding css classes to each group of fields?


Solution

  • The idea of ids is that they are a unique reference to an element and as such it is not legal (valid HTML) to have multiple elements referring to the same id. If you want to avoid collisions and still identify the element you could use a combination of classes.

    For example if you have 2 forms asking for a name (as in your previous comment) you could use:

    <input type="text" class="ajax firstName" /> 
    

    For the form generated by ajax, and

    <input type="text" class="initial-form firstName" /> 
    

    For the initial form on the webpage.

    Equally you could use the data- attribute to hold a namespace. E.g:

    <input type="text" data-namespace="ajax" class="firstName" />
    

    (This can be accessed through Javascript with element.dataset["namespace"])