我使用引导程序材料设计来显示带有其值的下拉列表。我需要使用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>
JQuery
**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)
您可以选择第一个选项并将其selected
属性更改为true,如下所示:
function clear_value() {
$('#ddID option[value=""]').prop('selected', true);
}
$('#clear').on('click', (e) => {
e.preventDefault();
clear_value();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>
<button id="clear">Clear Value</button>