frequent
frequent

Reputation: 28493

Is there validate-able way to use HTML label and input elements and the input not having an id?

I'm using Jquery Mobile for an application, which has a login popup on every page. The problem is, Jquery Mobile will always have at least 2 pages in the DOM, so I will have two popups and login forms in the DOm, forcing me to find a way to avoid duplicate id-attributes.

I worked around this by omitting the id attributes on the login form inputs, so I'm doing this:

 <label for="email" class="inFieldLabel">#tx_email#</label>
 <input autocomplete="off" type="email" name="email" value="#XMLFormat( lostPass.email )#" class="required">

Which works fine visually, but produces a validation error, because:

 The for attribute of the label element must refer to a form control.

Question:
Is there a way to pass validation without using an id attribute? What would be workarounds?

Note: I can't use a global login popup, because this is not supported by Jquery Mobile at the moment, so I'm stuck with a popup on every page.

Thanks for insights!

Upvotes: 2

Views: 2000

Answers (2)

Quentin
Quentin

Reputation: 943510

Put the form control the label applies to inside the label.

<label> text <input> </label>

Upvotes: 1

Matthew
Matthew

Reputation: 8416

Assuming 2 things: that you aren't going to be using IDs to style your form and you have a FORM tag around each popup. This code will append a random number to the IDs/FORs of the elements of your form. You'll likely need to pass this number to your validate routine as well.

jQuery("FORM").each(function()
{
  var randomNum = Math.random()*1000;
  var jForm = jQuery(this);
  jForm.find("INPUT").each(function()
  {
    this.id+=randomNum;        
  });
  jForm.find("LABEL").each(function()
  {
    jQuery(this).attr("for",jQuery(this).attr("for")+randomNum);
  });
});

...

validateForm(form, randomNum);

That's one way to keep the IDs on your forms unique.

I guess I'm assuming you're using the Validate plugin as well. If it's any help, you can use multiple non-unique IDs for your forms/elements as long as you pass Validate unique selectors like "#page-1 #popup-form #myInput" or "#page-2 #popup-form #myInput".

More edits:

Wait, are you looking for this? You can reference a form and it's controls via name instead of id using the forms object.

<form name="formNameAttribute">
  <input name="inputNameAttribute" value="some value" />
</form>

<script>
var inputValue=document.forms["formNameAttribute"]["inputNameAttribute"].value;
</script>

Upvotes: 1

Related Questions