本文介绍了如何动态更新实现< select&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带几个选项的选择标签.我正在使用materizlizecss select,并且我想根据特定条件使用javascript禁用某些选项.我已经阅读了另一篇有关如何执行此操作的文章,但是我需要在没有jquery的情况下进行操作.当我尝试时,什么也没发生.控制台中也没有错误或警告.

I have a select tag with several options. I am using materizlizecss select, and I would like to use javascript to disable certain options based on certain conditions. I have read another post on how to do this, but I need to do it without jquery. When I try it, nothing happens. No errors or warnings in the console either.

<form id="code-form">
            <h4 style="color: black;">Generate Code</h4>
            <div class="input-field">
                <select name="security-select" id="security-select">
                  <option style="display: none;" id="webmaster-value" value="1">Webmaster</option>
                  <option id="scoutmaster-value" value="2">Scoutmaster</option>
                  <option id="general-admin-value" value="3">General Admin</option>
                  <option id="spl-value" value="4">Senior Patrol Leader</option>
                  <option selected id="standard-user-value" value="5">Standard User</option>
                </select>
            </div>
            <button class="btn deep-purple" id="add-code">Generate Code</button>
        </form>

.

 if (security == '2') {
        document.querySelector('#webmaster-value').setAttribute('disabled', 'disabled')
    }

推荐答案

编辑后必须重新初始化选择字段

You have to Re-Initialize a select field after edited it

document.addEventListener('DOMContentLoaded', function () {
  var elems = document.querySelectorAll('select');
  var instances = M.FormSelect.init(elems);
});

document.getElementById("change-code").addEventListener("click", function () {
  document.querySelector('#webmaster-value').setAttribute('disabled', 'disabled');
  // Re-Initialize select
  var elems = document.querySelectorAll('select');
  var instances = M.FormSelect.init(elems);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<form id="code-form">
    <h4 style="color: black;">Generate Code</h4>
    <div class="input-field">
        <select name="security-select" id="security-select">
            <option style="display: none;" id="webmaster-value" value="1">Webmaster</option>
            <option id="scoutmaster-value" value="2">Scoutmaster</option>
            <option id="general-admin-value" value="3">General Admin</option>
            <option id="spl-value" value="4">Senior Patrol Leader</option>
            <option selected id="standard-user-value" value="5">Standard User</option>
        </select>
    </div>
    <button type="button" class="btn deep-purple" id="change-code">Press to disable</button>
</form>

这篇关于如何动态更新实现&lt; select&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:55