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).

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

  1. https://luckmorecasino-vhod.today/

    Я искал лакмор казино актуальное зеркало и перепробовал много ссылок. Некоторые вообще не открывались. Этот вариант оказался самым стабильным. Сейчас использую его

  2. windsor horse racing results monday​

    Here is my webpage :: epsom derby ante post betting​;
    Nona,

  3. What’s up to every one, the contents present at this site are in fact amazing for people experience,
    well, keep up the nice work fellows.

    my homepage; can you make money off casinos (Martha)

  4. лакмор казино вход
    Если ищешь актуальное зеркало Luckmore Casino, лучше сразу сохранять рабочие ссылки. Я сам несколько раз натыкался на нерабочие сайты и приходилось заново искать вход. В итоге этот вариант показался наиболее стабильным. Сейчас пользуюсь им чаще всего


  5. лакмор казино

    Если нужен быстрый вход в luckmore casino, лучше пользоваться проверенными ссылками. Я тестировал разные варианты и не все оказались рабочими. Этот сайт показывает нормальную стабильность. Можно спокойно заходить

  6. https://luckmorecasino-vhod.today/

    Когда нужен вход в luckmore casino, часто приходится перебирать разные сайты. Не все ссылки открываются нормально и часть просто не работает. Я протестировал несколько вариантов и этот оказался самым удобным. Можно заходить без лишних проблем

  7. luckmore

    Я искал лакмор казино актуальное зеркало и перепробовал много ссылок. Некоторые вообще не открывались. Этот вариант оказался самым стабильным. Сейчас использую его

  8. 想要快速解决语言障碍?选择有道翻译(网易有道翻译)即可轻松实现全球沟通!作为领先的智能翻译平台,“有道翻译官网”提供多语种即时翻译服务,让学习与工作更加高效。

    通过“有道翻译下载”,你可以体验最先进的AI翻译技术,无论是文本、语音还是图片内容,都能快速精准翻译。无论你是学生、外贸从业者还是旅行者,有道翻译都能满足你的各种需求。

    网易有道翻译不断优化算法,提升翻译质量,使表达更加自然流畅。同时支持离线使用与多设备同步,让你随时随地都能使用翻译功能。

    有道(Youdao)作为国内领先的教育与语言服务品牌,一直致力于打造最智能的语言解决方案。选择有道翻译,就是选择高效、准确与专业。

  9. luckmore

    Когда ищешь лакмор казино сайт, важно чтобы он был актуальным. Я нашел этот вариант и он оказался рабочим. Пока без проблем

  10. Discover the amazing features of hghjfjdossa and elevate your experience today. The influence of hghjfjdossa improves performance and results in real-world contexts.

  11. работы по замене шпал Опытные инженеры-путейцы учитывают все факторы для обеспечения надежности и безопасности. Разработка проектов железнодорожных путей включает в себя выбор оптимальной трассы расчеты нагрузок подбор материалов и разработку мероприятий по охране окружающей среды.

  12. Эвакуатор спб Мы работаем чтобы вы могли продолжить свой путь без лишних хлопот.

  13. пакеты с бегунком по индивидуальным размерам Они выглядят более дорого и изысканно добавляя вашему бренду особый шарм.

  14. Всем любителям скачать майнкрафт пе в один клик Видео на ютубе Text Test.

  15. Стрижка без очереди запись Москва Начните свой бизнес с LANDSHI.RU по всей России Платформа для мастеров красоты по всей России: онлайн-запись продвижение в выбранном городе и выгодные тарифы. Всё что нужно чтобы клиенты находили вас. Для мастеров и салонов: создание профиля публикация услуг управление расписанием приём записей оформление и оплата подписки.Платформа LANDSHI работает связующем звеном которое помогает клиентам найти подходящих для себя мастеров а мастерам максимальное количество клиентов в сфере салонов красоты и барбершопов. LANDSHI — это сервис который позволяет: находить мастеров и салоны красоты просматривать услуги цены и отзывы записываться на приём и управлять своими записями онлайн 24/7.Основные возможности для клиентов: быстрый поиск специалистов запись на услуги управление визитами.

  16. Do you have a spam problem on this website; I also am a blogger and I was curious about your situation; many of us have created some nice procedures and we are looking to trade strategies with others be sure to shoot me an e-mail if interested. https://share.google/oS68mmEwFvEyJFIpq

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>