Невозможно изменить обязательный атрибут для HTML текстовых полей - PullRequest
0 голосов
/ 20 февраля 2020

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

Код ".required = true | false" JavaScript, похоже, работает с элементами выбранного типа, но не с элементами текстового типа. Вот мой код:

function ProjStrucHideShow(selection) {

  let d1 = document.getElementById("NameRow")
  let d2 = document.getElementById("ProjNameLabel")
  let d3 = document.getElementById("ProjName")
  let d4 = document.getElementById("ProgNameLabel")
  let d5 = document.getElementById("ProgName")
  let e1 = document.getElementById("StageRow")
  let e2 = document.getElementById("ProjStageLabel")
  let e3 = document.getElementById("ProjStage")
  let e4 = document.getElementById("ProgStageLabel")
  let e5 = document.getElementById("ProgStage")

  if (selection === "Project") {
    d1.style.display = "table-row";
    d2.style.visibility = "visible";
    d3.style.visibility = "visible";
    d3.required = true;
    d3.value = null;
    d4.style.visibility = "hidden";
    d5.style.visibility = "hidden";
    d5.required = false;
    d5.value = null;
    e1.style.display = "table-row";
    e2.style.visibility = "visible";
    e3.style.visibility = "visible";
    e3.required = true;
    e3.value = null;
    e4.style.visibility = "hidden";
    e5.style.visibility = "hidden";
    e5.required = false;
    e5.value = null;
  }

  if (selection === "Part of Program") {
    d1.style.display = "table-row";
    d2.style.visibility = "visible";
    d3.style.visibility = "visible";
    d3.required = true;
    d3.value = null;
    d4.style.visibility = "visible";
    d5.style.visibility = "visible";
    d5.required = true;
    d5.value = null;
    e1.style.display = "table-row";
    e2.style.visibility = "visible";
    e3.style.visibility = "visible";
    e3.required = true;
    e3.value = null;
    e4.style.visibility = "visible";
    e5.style.visibility = "visible";
    e5.required = true;
    e5.value = null;
  }

  if (selection === "Program") {
    d1.style.display = "table-row";
    d2.style.visibility = "hidden";
    d3.style.visibility = "hidden";
    d3.required = false;
    d3.value = null;
    d4.style.visibility = "visible";
    d5.style.visibility = "visible";
    d5.required = true;
    d5.value = null;
    e1.style.display = "table-row";
    e2.style.visibility = "hidden";
    e3.style.visibility = "hidden";
    e3.required = false;
    e3.value = null;
    e4.style.visibility = "visible";
    e5.style.visibility = "visible";
    e5.required = true;
    e5.value = null;
  }
}
<html>

<head>
</head>

<body>
  <form>
    <table>
      <tr id="ContactRow">
        <td id="ContactNameLabel" width="25%" nowrap required="required"><strong>Requestor Name*</strong></td>
        <td id="ContactName" width="25%"><input type="text" size="30" name="ContactName" required="required"></td>
        <td id="ContactPhoneLable" width="25%" nowrap><strong>Phone Number</strong></td>
        <td id="ContactPhone" width="25%"><input type="tel" size="30" name="ContactPhone"></td>
      </tr>

      <tr id="StructureRow">
        <td id="ProjStrucLabel" width="25%" nowrap><strong>Structure*</strong></td>
        <td width="25%">
          <select id="ProjStruc" name="ProjStruc" onchange="ProjStrucHideShow(this.value)" required="required">
            <option value="">-- Select an Option --</option>
            <option value="Project">Project, Stands Alone</option>
            <option value="Part of Program">Project, Part of Program/Initiative</option>
            <option value="Program">Program/Initiative</option>
          </select>
        </td>
      </tr>

      <tr id="NameRow" style="display:none">
        <td id="ProjNameLabel" width="25%" nowrap><strong>Project Name*</strong></td>
        <td id="ProjName" width="25%"><input type="text" maxlength="30" size="30" name="ProjName"></td>
        <td id="ProgNameLabel" width="25%" nowrap><strong>Program Name*</strong></td>
        <td id="ProgName" width="25%"><input type="text" maxlength="30" size="30" name="ProgName"></td>
      </tr>

      <tr id="StageRow" style="display:none">
        <td id="ProjStageLabel" width="25%" nowrap><strong>Project Stage*</strong></td>
        <td width="25%">
          <select id="ProjStage" name="ProjStage">
            <option value="">-- Select an Option --</option>
            <option value="Definition">Definition</option>
            <option value="Planning">Planning</option>
            <option value="Execution">Execution</option>
            <option value="Closure">Closure</option>
          </select>
        </td>
        <td id="ProgStageLabel" width="25%" nowrap><strong>Program Stage*</strong></td>
        <td width="25%">
          <select id="ProgStage" name="ProgStage">
            <option value="">-- Select an Option --</option>
            <option value="Definition">Definition</option>
            <option value="Planning">Planning</option>
            <option value="Execution">Execution</option>
            <option value="Closure">Closure</option>
          </select>
        </td>
      </tr>

      <tr>
        <td align="center" colspan="4">
          <input id="FormSubmit" name="FormSubmit" type="submit" value="   Submit   ">
        </td>
      </tr>
    </table>
  </form>
</body>

</html>

1 Ответ

0 голосов
/ 21 февраля 2020

Я считаю, что element.required = true; и element.required = false; действительны здесь, где они работают вживую:

enter image description here

Демонстрация: https://codepen.io/Alexander9111/pen/rNVMPKK

проблема была только в выборе элемента dom.

Входные теги находятся внутри элементов данных таблицы с идентификаторами "ProjName" и "ProgName":

<td id="ProjNameLabel" width="25%" nowrap><strong>Project Name*</strong></td>
<td id="ProjName" width="25%"><input type="text" maxlength="30" size="30" name="ProjName"></td>
<td id="ProgNameLabel" width="25%" nowrap><strong>Program Name*</strong></td>
<td id="ProgName" width="25%"><input type="text" maxlength="30" size="30" name="ProgName"></td>

Так что вам нужно изменить свой выбор dom следующим образом:

  let d2 = document.getElementById("ProjNameLabel")
  let d3 = document.querySelector("#ProjName > input")
  let d4 = document.getElementById("ProgNameLabel")
  let d5 = document.querySelector("#ProgName  > input")

Тогда все будет работать, как и ожидалось.

Я также добавил условие, когда пользователь повторно выбирает "- - Выберите опцию - «опция».

Полная рабочая демонстрация: https://codepen.io/Alexander9111/pen/rNVMPKK

И ниже:

enter image description here

function ProjStrucHideShow(selection) {

  let d1 = document.getElementById("NameRow")
  let d2 = document.getElementById("ProjNameLabel")
  let d3 = document.querySelector("#ProjName > input")
  let d4 = document.getElementById("ProgNameLabel")
  let d5 = document.querySelector("#ProgName  > input")
  let d6 = document.getElementById("ProjDateLabel")
  let d7 = document.querySelector("#ProjDate  > input")
  let e1 = document.getElementById("StageRow")
  let e2 = document.getElementById("ProjStageLabel")
  let e3 = document.getElementById("ProjStage")
  let e4 = document.getElementById("ProgStageLabel")
  let e5 = document.getElementById("ProgStage")
  let submit = document.getElementById('FormSubmit');

  if (selection === "Select") {
    d1.style.display = "none" ;
    d2.style.visibility = "hidden" ;
    d3.style.visibility = "hidden" ;
    d3.required = false;
    d3.value = null ;
    d4.style.visibility = "hidden" ;
    d5.style.visibility = "hidden" ;
    d5.required = false;
    d5.value = null ;
    e1.style.display = "none" ;
    e2.style.visibility = "hidden" ;
    e3.style.visibility = "hidden" ;
    e3.required = false;
    e3.value = null ;
    e4.style.visibility = "hidden" ;
    e5.style.visibility = "hidden" ;
    e5.required = false;
    e5.value = null ;
    submit.disabled = true;
    d7.required = false;
    d7.value = "";
  } else {
    submit.disabled = false;
    submit.disabled = false;
    d7.required = true;
  }

  if (selection === "Project") {
    d1.style.display = "table-row" ;
    d2.style.visibility = "visible" ;
    d3.style.visibility = "visible" ;
    d3.required = true ;
    d3.value = null ;
    d4.style.visibility = "hidden" ;
    d5.style.visibility = "hidden" ;
    d5.required = false;
    d5.value = null ;
    e1.style.display = "table-row" ;
    e2.style.visibility = "visible" ;
    e3.style.visibility = "visible" ;
    e3.required = true ;
    e3.value = null ;
    e4.style.visibility = "hidden" ;
    e5.style.visibility = "hidden" ;
    e5.required = false;
    e5.value = null ;
  }

  if (selection === "Part of Program") {
    d1.style.display = "table-row" ;
    d2.style.visibility = "visible" ;
    d3.style.visibility = "visible" ;
    d3.required = true ;
    d3.value = null ;
    d4.style.visibility = "visible" ;
    d5.style.visibility = "visible" ;
    d5.required = true ;
    d5.value = null ;
    e1.style.display = "table-row" ;
    e2.style.visibility = "visible" ;
    e3.style.visibility = "visible" ;
    e3.required = true ;
    e3.value = null ;
    e4.style.visibility = "visible" ;
    e5.style.visibility = "visible" ;
    e5.required = true ;
    e5.value = null ;
  }

  if (selection === "Program") {
    d1.style.display = "table-row" ;
    d2.style.visibility = "hidden" ;
    d3.style.visibility = "hidden" ;
    d3.required = false ; //.removeAttribute('required');
    d3.value = null ;
    d4.style.visibility = "visible" ;
    d5.style.visibility = "visible" ;
    d5.required = true ;
    d5.value = null ;
    e1.style.display = "table-row" ;
    e2.style.visibility = "hidden" ;
    e3.style.visibility = "hidden" ;
    e3.required = false ; //.removeAttribute('required');
    e3.value = null ;
    e4.style.visibility = "visible" ;
    e5.style.visibility = "visible" ;
    e5.required = true ;
    e5.value = null ;
  }
}
<html>
  <head>
  </head>
  <body>
    <form>
      <table>
        <tr id="ContactRow">
          <td id="ContactNameLabel" width="25%" nowrap required="required"><strong>Requestor Name*</strong></td>
          <td id="ContactName" width="25%"><input type="text" size="30" name="ContactName" required="required"></td>
          <td id="ContactPhoneLable" width="25%" nowrap><strong>Phone Number</strong></td>
          <td id="ContactPhone" width="25%"><input type="tel" size="30" name="ContactPhone"></td>
        </tr>

        <tr id="StructureRow">
          <td id="ProjStrucLabel" width="25%" nowrap><strong>Structure*</strong></td>
          <td width="25%">
            <select id="ProjStruc" name="ProjStruc" onchange="ProjStrucHideShow(this.value)" required="required">
              <option value="Select">-- Select an Option --</option>
              <option value="Project">Project, Stands Alone</option>
              <option value="Part of Program">Project, Part of Program/Initiative</option>
              <option value="Program">Program/Initiative</option>
            </select>
          </td>
        </tr>

        <tr id="NameRow" style="display:none">
          <td id="ProjNameLabel" width="25%" nowrap><strong>Project Name*</strong></td>
          <td id="ProjName" width="25%"><input type="text" maxlength="30" size="30" name="ProjName"></td>
          <td id="ProgNameLabel" width="25%" nowrap><strong>Program Name*</strong></td>
          <td id="ProgName" width="25%"><input type="text" maxlength="30" size="30" name="ProgName"></td>
        </tr>

        <tr id="StageRow" style="display:none">
          <td id="ProjStageLabel" width="25%" nowrap><strong>Project Stage*</strong></td>
          <td width="25%">
            <select id="ProjStage" name="ProjStage">
              <option value="">-- Select an Option --</option>
              <option value="Definition">Definition</option>
              <option value="Planning">Planning</option>
              <option value="Execution">Execution</option>
              <option value="Closure">Closure</option>
            </select>
          </td>
          <td id="ProgStageLabel" width="25%" nowrap><strong>Program Stage*</strong></td>
          <td width="25%">
            <select id="ProgStage" name="ProgStage">
              <option value="">-- Select an Option --</option>
              <option value="Definition">Definition</option>
              <option value="Planning">Planning</option>
              <option value="Execution">Execution</option>
              <option value="Closure">Closure</option>
            </select>
          </td>
        </tr>
        <tr id="DateRow" style="display:table-row" >
          <td id="ProjDateLabel" width="25%" nowrap><strong>Project Date*</strong></td>
          <td id="ProjDate"><input type="date" id="start" name="project-start"
         value=""
         min="2018-01-01" max="2020-12-31"></td>
        </tr>
        <tr>
          <td align="center" colspan="4">
            <input disabled id="FormSubmit" name="FormSubmit" type="submit" value="   Submit   " >
          </td>
        </tr>
      </table>
    </form>
  </body>
  </html>

ОБНОВЛЕНИЕ - да, это также работает для выбора даты:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...