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,458 thoughts on “jQuery plugin to associate label “for” attribute with form controls that have dynamic id’s

  1. velora casino official

    Недавно увидел Velora Casino и решил подписаться на официальный канал. Теперь все публикации появляются прямо в ленте telegram

  2. MexiCare Direct: pharmacies in mexico – MexiCare Direct

  3. mexico drug store: MexiCare Direct – MexiCare Direct

  4. Easy North RX: Easy North RX – pharmacy wholesalers canada

  5. mexican pharmacy las vegas: online mexico pharmacy – MexiCare Direct

  6. ссылка

    Если интересуют новости Velora Casino, официальный канал поможет быстро найти актуальную информацию. Все публикации доступны в удобном формате

  7. velora casino

    Недавно искал новости Velora Casino и в итоге нашел официальный telegram. Теперь вся актуальная информация находится в одном месте. Очень удобный формат

  8. velora casino

    Velora Casino продолжает развивать свое сообщество в telegram. Благодаря этому подписчики быстро узнают о новых материалах и объявлениях

  9. velora casino official

    Velora Casino регулярно публикует важные объявления через telegram. Благодаря этому подписчики получают свежую информацию максимально быстро. Канал активно развивается

  10. buy medicines online in india: mail order pharmacy india – foreign online pharmacy

  11. Hello friends I came across a 176 great tool that I think you should visit. This tool is packed with a lot of useful information that you might find valuable. It has everything you could possibly need so be sure to give it a visit https://inkedwit.com/financial-prudence-for-gamers/ Additionally remember not to overlook everyone which you constantly are able to in this article locate responses to your the absolute complicated questions. The authors made an effort — present the complete information using the most most easy-to-grasp way.

  12. canadian pharmacies shipping to usa: safe online pharmacies in canada – canadian drugs online

  13. Easy North RX: Easy North RX – best rated canadian pharmacy

  14. indian pharmacies safe indian pharmacy online best online pharmacy no prescription

  15. Добро пожаловать в blacksprut Marketplace blsp at топ в 2026 году Сотни магазинов с оптовыми и розничными предложениями рады показать вам новый уровень отношения к каннабису и грибам. bs2best at blsp at blacksprut

  16. велора казино

    Если нужен официальный канал Velora Casino, лучше использовать именно этот источник. Здесь регулярно публикуются актуальные новости проекта

  17. indian pharmacy paypal: Flexi Meds India – reliable online pharmacy

  18. велора казино канал

    Когда ищешь актуальные обновления по Velora Casino, официальный telegram помогает быстро найти всю необходимую информацию. Канал остается одним из главных источников новостей проекта

  19. Промокод при регистрации 1xbet на 32500 рублей. Этот код нужно ввести при регистрации в соответствующее поле. 1Xbet промокод можно использовать только один раз но им можно делиться с друзьями. Регистрация по номеру телефона — простой способ создать аккаунт. После получения данных для входа остаётся лишь ввести логин и пароль. Используй актуальный промокод 1xbet и увеличь первый депозит до 32500 рублей в букмекере 1хБет. На платформе действует программа лояльности которая помогает игрокам получать до дополнительных процентов от первого депозита.

  20. buy prescription drugs from india: Flexi Meds India – shop medicine online

  21. тут

    Velora Casino поддерживает активный telegram-канал для своей аудитории. Там регулярно публикуются свежие новости и полезные материалы

  22. official velora casino

    Если интересует Велора Казино, официальный канал поможет всегда оставаться в курсе последних событий проекта

  23. Velora casino

    Velora Casino поддерживает активный telegram-канал для своей аудитории. Там регулярно публикуются свежие новости и полезные материалы

  24. canadianpharmacyworld com: canadian pharmacy ed medications – Easy North RX

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>