清除材料设计下拉值会导致错误

我正在使用引导材料设计来显示带有它们值的下拉列表。我需要使用 JQuery 或任何其他方法清除所选值,因为我尝试执行的操作导致了错误。


我浏览了 md bootstrap 的文档,但没有任何运气。


HTML代码


<div class="form-group">

        <label for="ddID">Select list:</label>

        <select id="ddID" class="selectpicker mdb-select md-form" required>

            <option value="" disabled selected></option>

            <option value="1">1</option>

            <option value="2">2</option>

            <option value="3">3</option>

            <option value="4">4</option>

            <option value="5">5</option>

        </select>  

</div>

查询


**1st attempt**

function clear_value() {

  $('#ddID').removeAttr('required');

  $('#ddID').val('');

 }


**2nd attempt**

function clear_value() {

  $("#ddID").material_select("destroy");

  $("#ddID").material_select();

 }


**3rd attempt**

function clear_value() {

  $('select.mdb-select').materialSelect({ destroy: true });

 }


**4th attempt**

function clear_value() {

  $(".active").removeClass();

 }

错误


Uncaught TypeError: Cannot read property 'setAttribute' of null

    at Object.applyStyleOnLoad [as onLoad] (applyStyle.js:66)

    at index.js:69

    at Array.forEach (<anonymous>)

    at new Popper (jq.js:67)

    at Dropdown.toggle (dropdown.js:176)

    at HTMLInputElement.<anonymous> (dropdown.js:267)

    at HTMLInputElement.dispatch (jquery-3.4.1.min.js:2)

    at HTMLInputElement.v.handle (jquery-3.4.1.min.js:2)


慕妹3242003
浏览 89回答 1
1回答

一只萌萌小番薯

您可以选择第一个选项并将其selected属性更改为 true ,如下所示:function clear_value() {&nbsp; $('#ddID option[value=""]').prop('selected', true);}$('#clear').on('click', (e) => {&nbsp; e.preventDefault();&nbsp;&nbsp;&nbsp; clear_value();});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div class="form-group">&nbsp; &nbsp; &nbsp; &nbsp; <label for="ddID">Select list:</label>&nbsp; &nbsp; &nbsp; &nbsp; <select id="ddID" class="selectpicker mdb-select md-form" required>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option value="" disabled selected></option>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option value="1">1</option>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option value="2">2</option>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option value="3">3</option>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option value="4">4</option>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <option value="5">5</option>&nbsp; &nbsp; &nbsp; &nbsp; </select>&nbsp;&nbsp;</div><button id="clear">Clear Value</button>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript