首页 > 解决方案 > 选择选项时更改必填字段形式

问题描述

我有如下表格

       <form>
        <div class="6 op" style="display: none;">
        <div class="form-group">Service</label>
              <select class="form-control" id="exampleFormControlSelect1" required>
                 <option></option>
                 <option>Fiber</option>
                 <option>Hotspot</option>
              </select>
           </div>
           <div class="form-group">
              <label for="exampleFormControlInput1">Capacity</label>
              <input type="text" class="form-control" id="formGroupExampleInput" placeholder="example: 1" required>
              <select class="form-control" id="exampleFormControlSelect1" required>
                 <option>Mbps</option>
                 <option>Gbps</option>
              </select>
           </div>
           <div class="form-group">
              <label for="exampleFormControlTextarea1">Notes</label>
              <textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
           </div>
           <input type="submit">
        </div>
     </form>

在上面的代码中,requiredservicecapacity。我想知道如何仅当我在字段中选择选项时自动添加required到字段。notesHotspotservice

你知道怎么做吗 ?

谢谢

标签: javascriptjqueryhtml

解决方案


您可以将onchange事件处理程序添加到选择选项,并作为参数传递所选选项的值。在这种情况下,当值是热点时,您可以使用setAttribute将属性添加required到 textarea 或者将其设置为 false 或使用删除它removeAttribute。dom 元素的 id 也必须是唯一的

let txtArea = document.getElementById('exampleFormControlTextarea1');

function changeService(val) {
  if (val.toLowerCase() === 'hotspot') {
    txtArea.setAttribute('required', true)

  } else {
    txtArea.setAttribute('required', false)

  }

}
<form>
  <div class="6 op" style="">
    <div class="form-group"><label for='exampleFormControlSelect1'>Service</label>
      <select onchange='changeService(this.value)' class="form-control" id="exampleFormControlSelect1" required>
        <option></option>
        <option>Fiber</option>
        <option>Hotspot</option>
      </select>
    </div>
    <div class="form-group">
      <label for="exampleFormControlInput2">Capacity</label>
      <input type="email" class="form-control" id="exampleFormControlInput1" placeholder="example: 1" required>
      <select class="form-control" id="exampleFormControlSelect2" required>
        <option>Mbps</option>
        <option>Gbps</option>
      </select>
    </div>
    <div class="form-group">
      <label for="exampleFormControlTextarea1">Notes</label>
      <textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea>
    </div>
    <input type="submit">
  </div>
</form>


推荐阅读