jQuery plugin to associate label “for” attribute with form controls that have dynamic id’s

For whatever reason, you can’t associate your labels with your form controls implicitly by wrapping both the label text and the control in a <label> element:

<label>
  Email address: <input type="email" name="email" value="" placeholder="you@example.com"/>
</label>

You’ve had to explicitly state the form control you want the label to be associated with:

<label for="email">Email address:</label>
<input id="email" type="email" name="email" value="" placeholder="you@example.com"/>

…but your framework has other ideas, it decides to commandeer your precious “id” attribute and change it from a simple and beautiful “email” into a junky “dnn_ctr1163_RegistrationForm_email”. *cough* DotNetNuke *cough*, but also *cough* Wicket *cough* and probably a whole load of others.

The problem is now that your label is no longer associated with your form control, and there isn’t a simple fix, like, for example, change the for attribute to read “dnn_ctr1163_RegistrationForm_email”, because the numbers in the id change each time you refresh the page. The ID is dynamic, and you are receiving accessibility black stars.

So, luckily I noticed that often the id will change, but the framework will leave your originally intended id somewhere in there. I’ve written a jQuery plugin to look at label for attributes and try to find the form control you intended to associate it with before your server side framework so rudely changed it.

How to use

  1. Download the plugin and add it to your page
  2. Select the labels you want to re-associate and call the function eg. $(‘label’).fuzzyFor();

TODO

The plugin finds matches by looking for input, select and textarea elements in the document and checking to see if the for attribute in your label element appears in the id attribute of the form control. At the moment if more than one match is found, it just uses the first (which is probably good enough for most). However, it should probably do something a bit more clever and use the form control that is closest to the label (I’m reasoning that you normally put your label’s close to your controls).

14,394 thoughts on “jQuery plugin to associate label “for” attribute with form controls that have dynamic id’s

  1. bouka spins no deposit bonus code, 10 dollar minimum deposit usa online
    casino 2021 and real money gambling online united states, or quatro casino united states

    my blog post :: don’t come craps strategy, Esther,

  2. farmacia online barata y fiable farmacias online seguras farmacia online madrid

  3. farmacias online seguras: farmacia en casa online descuento – farmacia online barata y fiable

  4. farmacias online baratas farmacia online envГ­o gratis farmacia online barcelona

  5. farmacias online seguras п»їfarmacia online espaГ±a farmacia online barata y fiable

  6. farmacia online espaГ±a envГ­o internacional farmacia online barata farmacia online barata y fiable

  7. Viagra vente libre allemagne: Viagra 100 mg sans ordonnance – Acheter viagra en ligne livraison 24h

  8. Viagra sans ordonnance 24h Amazon Prix du Viagra 100mg en France Acheter viagra en ligne livraison 24h

  9. yard win tg
    ?
    Когда у кого?то из друзей возникает вопрос «почему сайт yard win Casino не открывается?», проще отправить ему ссылку на официальный телеграм?канал, чем объяснять длинными текстами; там он сам найдёт актуальное зеркало и инструкцию.

  10. casino yard win
    ?
    Тем, кто играет с разных устройств, официальный тг?канал yard win Casino заменяет сразу и новостную ленту, и поддержку: там публикуют информацию о техработах, лимитах на вывод, новых методах оплаты и заранее предупреждают, если какой?то платёжный сервис временно недоступен.

  11. order from mexico mexican pharmacies that ship to us mexico pharmacy

  12. yardwin
    ?
    Думаю, если кому-то лень читать большие обзоры, телеграм – идеальный вариант: короткие посты, сразу ссылка «зеркало на сегодня» и пара строк, что нового по бонусам.

  13. Хотите устроить вечеринку с друзьями тогда квартира на сутки с просторной гостиной и караоке станет лучшим выбором без соседей снизу и ограничений по времени как в клубах квартиры посуточно Сдаётся квартира с аквагримом и костюмами для детей где малыши могут превращаться в супергероев или принцесс целый день без ограничений и шума студия на сутки Квартира с историческим интерьером и лепниной на потолке подарит ощущение дворянской усадьбы в центре мегаполиса с современными удобствами и тишиной жилье на сутки у вокзала

  14. yard win
    ?
    Игрокам, которые боятся оставлять почту на сторонних обзорниках ради рассылок с зеркалами, проще и безопаснее подписаться на официальный yard win Casino в тг: там нет лишнего спама, только рабочие ссылки и конкретные новости по бонусам и промо.

  15. mexico prescription online purple pharmacy mexico is mexipharmacy legit

  16. mexico prescription online: mexican pharmacy prices – mexican pharmacies online drugs

  17. ярд вин казино
    ?
    Иногда в канале появляются мини?обзоры слотов, которые лучше отыгрывают бонусы; для тех, кто гоняется за фриспинами, это полезнее, чем общие статьи на сайтах.

  18. Prix du Viagra 100mg en France Viagra pas cher livraison rapide france Viagra pas cher inde

  19. yardwin telegram
    ?
    Удобно, что новые зеркала появляются и на русском, и на английском, можно скинуть ссылку друзьям из других стран без страха, что их перебросит куда?то ещё.

  20. yard win casino
    ?
    Даже если вы не сидите в тг каждый день, можно просто закрепить чат yard win Casino вверху: когда понадобится рабочее зеркало или apk, вы сразу увидите нужный канал и не будете путаться между клоновскими каналами с похожими названиями.

  21. best online mexican pharmacy hydrocodone mexico pharmacy mail order pharmacies

  22. casino yard win
    ?
    Смешно, но я нашёл этот канал не через рекламу, а через комментарий на форуме, где человек честно написал, что только там нашёл нормальную ссылку на yard win.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>