Skip to content

Instantly share code, notes, and snippets.

@mrmanc
Created June 14, 2012 22:07
Show Gist options
  • Save mrmanc/2933264 to your computer and use it in GitHub Desktop.
Save mrmanc/2933264 to your computer and use it in GitHub Desktop.
Regexs to fix forms disconnected labels
I've been irritated with the hundreds of label tags in our sites with no 'for' attribute. This leads to forms where clicking the label does not put focus into that field. So I've written these operations to bulk fix this problem.
There are two steps, because if you've not used 'for' attributes, you probably don't have 'id' attributes on your form fields. So I've extracted the 'name' attribute from the form field and name-spaced it. Caution: if you have more than one form on the page you might end up with two elements with the same 'id' attribute, which would be improper.
So this:
<label>Forename</label>
<input name="forename">
becomes:
<label for="auto-generated-id-forename">Forename</label>
<input id="auto-generated-id-forename" name="forename">
1. Generate 'id' attributes for form fields with none based on their 'name' attribute.
Find: (<(?:input|textarea|select))((?:(?!id=).)*name=")([^"]*)("(?:(?!id=).)*>)
Replace with: $1 id="auto-generated-id-$3"$2$3$4
2. Add 'for' attributes to label tags immediately preceding a form field with an 'id' attribute.
Find: (<label)([^>]*>[^<]*</label>[^<]*<(?:input|textarea|select)[^>]*id=")([^"]*)("[^>]*>)
Replace with: $1 for="$3"$2$3$4
These operations are designed for use with Eclipse, and may work elsewhere (but I haven't tried).
See here for background reading on lookaround: http://www.regular-expressions.info/lookaround2.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment