【问题标题】:How do I disable a dropdown menu based on another dropdown menu value如何根据另一个下拉菜单值禁用下拉菜单
【发布时间】:2021-12-31 12:21:22
【问题描述】:

下面是我的 html 代码和脚本,用于从下拉菜单中选择多个选项。

我想在一个下拉列表中选择特定值时为用户提供一个额外的选项,以便用户提供额外的输入。

当在第一个下拉菜单中选择“Plant Machine”时,下面的脚本似乎没有禁用第二个下拉菜单:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/harvesthq/chosen/gh-pages/chosen.jquery.min.js"></script>
<link href="https://cdn.rawgit.com/harvesthq/chosen/gh-pages/chosen.min.css" rel="stylesheet" />
<div class="control-group ">

  <label for="company" class="sr-only">machine</label>
  <div class="controls">
    <select name="company" class="form-control" id="company" required>
      <option></option>
      <option value="Hire">Plant Hire</option>
      <option value="Machine">Plant Machine</option>
      <option value="Store">Plant Store</option>
      <option></option>
    </select>
  </div>
</div>

<div class="control-group">
  <div class="controls">
    <label for="machine" class="sr-only">Machinery</label>
    <select name="machine" id="machine" data-placeholder="Select 1 or Multiple Machinery" multiple class="chosen-select">
      <option></option>
      <option>TLB 4x4 with a bucket</option>
      <option>Tipper truck 10m^3</option>
      <option>Grader</option>
      <option>Roller (10ton)</option>
      <option>Excavator 30ton with a bucket </option>
      <option>Excavator 30ton with a pecker</option>
      <option>3.5ton pecker for excavator</option>
      <option>TLB 4x4 with a pecker</option>
      <option></option>
    </select>
  </div>
</div>

<script>
  document.getElementById('company').onchange = function() {
  
    if (this.value == "Machine") {
      document.getElementById('machine').removeAttribute('disabled');
    } else {
      document.getElementById('machine').setAttribute('disabled', true);
    }
    
  }
</script>

<script>
  $(".chosen-select").chosen({
    no_results_text: "Nothing Selected"
  })
</script>

【问题讨论】:

标签: javascript html script


【解决方案1】:

改变else条件下的代码如下:

document.getElementById('machine').disabled=true;

【讨论】:

  • 我改了,结果还是一样
  • 请检查更新的答案。
【解决方案2】:

因为您有一个样式,它使用其他元素作为呈现的选择。选择本身有一个 display: none 样式,它实际上被禁用了。使用类似指针事件的东西:无;在 id="machine_chosen" 的 div 上。您也可以寻找其他选项来禁用它。

也加上上面交替使用

document.getElementById('machine').disabled = 'false';

【讨论】:

  • 感谢使用 `document.getElementById('machine_chosen').style.removeProperty('pointer-events'); ` 和 document.getElementById('machine_chosen').style.setProperty('pointer-events', 'none');
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多