Подтвердить что ты не робот

Как я могу использовать атрибут FOR тега LABEL без атрибута ID в теге INPUT

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

<html>
 <head>
  <title>Input ID creates problems</title>
  <style type="text/css">
   #prologue, #summary { margin: 5em; }
  </style>
 </head>
 <body>
  <h1>Input ID creates a bug</h1>
  <p id="prologue">
   In this example, I make a list of checkboxes representing things which could appear in a book. If you want some in your book, you check them:
  </p>
  <form>
   <ul>
    <li>
     <input type="checkbox" id="prologue" />
     <label for="prologue">prologue</label>
    </li>
    <li>
     <input type="checkbox" id="chapter" />
     <label for="chapter">chapter</label>
    </li>
    <li>
     <input type="checkbox" id="summary" />
     <label for="summary">summary</label>
    </li>
    <li>
     <input type="checkbox" id="etc" />
     <label for="etc">etc</label>
     <label>
    </li>
   </ul>
  </form>
  <p id="summary">
   For each checkbox, I want to assign an ID so that clicking a label checks the corresponding checkbox. The problems occur when other elements in the page already use those IDs. In this case, a CSS declaration was made to add margins to the two paragraphs which IDs are "prologue" and "summary", but because of the IDs given to the checkboxes, the checkboxes named "prologue" and "summary" are also affected by this declaration. The following links simply call a javascript function which writes out the element whose id is <a href="javascript:alert(document.getElementById('prologue'));">prologue</a> and <a href="javascript:alert(document.getElementById('summary'));">summary</a>, respectively. In the first case (prologue), the script writes out [object HTMLParagraphElement], because the first element found with id "prologue" is a paragraph. But in the second case (summary), the script writes out [object HTMLInputElement] because the first element found with id "summary" is an input. In the case of another script, the consequences of this mix up could have been much more dramatic. Now try clicking on the label prologue in the list above. It does not check the checkbox as clicking on any other label. This is because it finds the paragraph whose ID is also "prologue" and tries to check that instead. By the way, if there were another checkbox whose id was "prologue", then clicking on the label would check the one which appears first in the code.
  </p>
  <p>
   An easy fix for this would be to chose other IDs for the checkboxes, but this doesn't apply if these IDs are given dynamically, by a PHP скрипт for example.
   Another easy fix for this would be to write labels like this:
   <pre>
    &lt;label&gt;&lt;input type="checkbox" /&gt;prologue&lt;/label&gt;
   </pre>
   and not need to give an ID to the checkboxes. But this only works if the label and checkbox are next to each other.
  </p>
  <p>
   Well, that the problem. I guess the ideal solution would be to link a label to a checkboxe using another mechanism (not using ID). I think the perfect way to do this would be to match a label to the input element whose NAME (not ID) is the same as the label FOR attribute. What do you think?
  </p>
 </body>
</html>
4b9b3361

Ответ 1

Лучшее, на мой взгляд, то, что вы можете сделать, - переименовать все флажки, добавив некоторый префикс к их идентификаторам, например input

   <ul>
    <li>
     <input type="checkbox" id="input_prologue" />
     <label for="input_prologue">prologue</label>
    </li>
    <li>
     <input type="checkbox" id="input_chapter" />
     <label for="input_chapter">chapter</label>
    </li>
    <li>
     <input type="checkbox" id="input_summary" />
     <label for="input_summary">summary</label>
    </li>
    <li>
     <input type="checkbox" id="input_etc" />
     <label for="input_etc">etc</label>
    </li>
   </ul>

Таким образом, у вас не будет конфликтов с другими идентификаторами на странице, и щелчок на ярлыке переключит флажок без специальной функции javascript.

Ответ 2

он был разрешен здесь: fooobar.com/questions/90410/... просто сделайте это так

<label><input type="checkbox">Some text</label>

Ответ 3

РЕДАКТОР: В ретроспективе мое решение далека от идеала. Я рекомендую вместо этого использовать "неявную ассоциацию ярлыков", как показано в этом ответе: fooobar.com/questions/90410/...

Мое предложенное, менее идеальное решение ниже:

Эта проблема может быть легко решена с помощью небольшого javascript. Просто добавьте следующий код в один из ваших файлов js страницы, чтобы дать тегам <label> следующее поведение:

При нажатии метки:

Если на странице есть элемент с id, соответствующий атрибуту label for, верните функциональность по умолчанию и сфокусируйте этот ввод.

Если совпадение не найдено с помощью id, найдите дочерний элемент label с class, соответствующий атрибуту label for, и сосредоточьте его.

Это означает, что вы можете выложить свои формы следующим образом:

<form>
    <label for="login-validation-form-email">Email Address:</label>
    <input type="text" class="login-validation-form-email" />
</form>

Увы, фактический код:

$(function(){
    $('body').on('click', 'label', function(e){
        var labelFor = $( this ).attr('for');
        if( !document.getElementById(labelFor) ){
            e.preventDefault(); e.stopPropagation();
            var input = $( this ).siblings('.'+labelFor);
            if( input )
                input[0].focus();
        }
    })
});

Примечание. Это может вызвать проблемы при проверке вашего сайта на основе спецификации W3C, поскольку атрибут <label> for должен всегда иметь соответствующий элемент на странице с соответствующим идентификатором.

Надеюсь, это поможет!

Ответ 4

Проще говоря, идентификатор должен использоваться только один раз на странице, поэтому нет, они не будут разрабатывать обходной путь для нескольких ID на одной странице, которые не должны существовать.

Чтобы ответить на оставшуюся часть вопроса: нет, атрибут ID - это единственное, на что будет смотреть атрибут label for. Вы всегда можете использовать событие JavaScript onclick для извлечения ввода по имени и изменения его, хотя это кажется слишком сложным, когда вы можете просто исправить проблему с идентификатором, что будет иметь больший смысл.

Ответ 5

Возможно, простое простое решение будет использовать функцию uniqueid() php или другую альтернативу для программирования.