Используя проверку формы HTML5, могу ли я сделать поле ввода обязательным, только если выбран конкретный <option>из меню <select>? - PullRequest
0 голосов
/ 07 сентября 2018

Вот простая форма, которую я имею:

<form name="form_1">
  <fieldset>
    <select required name="choice">
      <option value="1">Choice 1</option>
      <option value="2">Choice 2</option>
      <option value="Other">Other</option>
    </select>
    <label for="other_text">If other, please specify: </label>
    <input id="other_text" name="other_text" size="30">
  </fieldset>
</form>

Как сделать поле ввода "other_text" required тогда и только тогда, когда для выбора "choice" установлено значение "Other"? По умолчанию поле ввода не должно быть обязательным. Может ли это быть сделано только с HTML5, или требуется Javascript?

Ответы [ 2 ]

0 голосов
/ 07 сентября 2018

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

<form name="form_1">
 <fieldset>
  <select required name="choice" id="choice" onchange="changeAttribute()">
   <option value="1">Choice 1</option>
   <option value="2">Choice 2</option>
   <option value="Other">Other</option>
  </select>
  <label for="other_text">If other, please specify: </label>
  <input id="other_text" name="other_text" size="30">
 </fieldset>
</form>

Затем используйте javascript для управления другим полем

function changeAttribute(){
    if(document.getElementById('choice').value == "Other") {
        document.getElementById('other_text').setAttribute("required","");
    }else{
        document.getElementById('other_text').removeAttribute("required","");
    }
}   
0 голосов
/ 07 сентября 2018

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

<form name="form_1">
    <fieldset>
        <select required name="choice">
          <option value="1">Choice 1</option>
          <option value="2">Choice 2</option>
          <option value="Other">Other</option>
        </select>
        <label for="other_text">If other, please specify: </label>
        <input id="other_text" name="other_text" size="30">
      </fieldset>
</form>
<script type="text/javascript">
    var form = document.getElementsByTagName('form')[0];
    form.onsubmit = function(e) {
        if (document.getElementsByTagName('select')[0].value == "Other") {
            e.preventDefault();
            // Block submitting form if option =  Other selected 
            document.getElementById('other_text').setAttribute('required', true);
            return false;
        }
        // Allow form submit otherwise
        document.getElementById('other_text').removeAttribute('required');
        console.log("Submitting form", e);
        return true;
    }
</script>
...