如果选择下拉列表,则显示额外的表单字段

时间:2017-02-05 01:29:20

标签: javascript jquery html

如果用户从下拉菜单中选择'Yes',我会尝试再显示两个表单字段。如果用户未从下拉列表中选择'Yes',则不需要添加两个额外字段,但是如果选择了'Yes',则必须填写这些字段表格提交。到目前为止,我有这个,但它不起作用。如果有人能指出这个问题,我们将不胜感激。

HTML:

<form id="form" method="post" action="action.php">

  <div class="form-group">
    <label class="control-label">Defect?</label>
    <select onclick='checkIfYes()' class="select form-control" id="defect" name="defect">
      <option id="No" value="No">No</option>
      <option id="Yes" value="Yes">Yes</option>
    </select>
  </div>

  <div id="extra" name="extra" style="display: none">

    <label class="control-label" for="desc">Description</label>
    <input class="form-control" type="text" id="desc" name="desc" required disabled>

    <label class="control-label" for="auth_by">Authorised By</label>
    <input class="form-control" type="text" id="auth_by" name="auth_by" required disabled>

  </div>

  <div class="form-group">
    <button class="btn btn-info" id="submit" name="submit" type="submit">Submit
    </button>
  </div>

</form>

JavaScript的:

function checkIfYes() {
  if (document.getElementById('defect').value == 'Yes') {
    document.getElementById('extra').style.display = '';
    document.getElementById('auth_by').disabled = false;
    document.getElementById('desc').disabled = false;
  } else {
    document.getElementById('extra').style.display = 'none';
  }
}

JSFiddle

1 个答案:

答案 0 :(得分:1)

checkIfYes需要在引用它的HTML之前定义。

我还建议将select onclick事件更改为onchange,以便仅在用户实际更改值时调用它

请参阅更新的小提琴:Updated Fiddle

<script>      
  function checkIfYes() {
      if (document.getElementById('defect').value == 'Yes') {
        document.getElementById('extra').style.display = '';
        document.getElementById('auth_by').disabled = false;
        document.getElementById('desc').disabled = false;
      } else {
        document.getElementById('extra').style.display = 'none';
  }
}
</script>
<form id="form" method="post" action="action.php">

  <div class="form-group">
    <label class="control-label">Defect?</label>
    <select onchange='checkIfYes()' class="select form-control" id="defect" name="defect">
      <option id="No" value="No">No</option>
      <option id="Yes" value="Yes">Yes</option>
    </select>
  </div>

  <div id="extra" name="extra" style="display: none">

    <label class="control-label" for="desc">Description</label>
    <input class="form-control" type="text" id="desc" name="desc" required disabled>

    <label class="control-label" for="auth_by">Authorised By</label>
    <input class="form-control" type="text" id="auth_by" name="auth_by" required disabled>

  </div>

  <div class="form-group">
    <button class="btn btn-info" id="submit" name="submit" type="submit">Submit
    </button>
  </div>

</form>