Search code examples
javascriptjquerytwitter-bootstrapmaterial-designdropdown

Clearing material design dropdown values results in an error


I'm using bootstrap material design to display a dropdown with their values. I need to clear the selected value using JQuery, or any other method since what I've attempted to do resulted in an error.

I've looked through md bootstrap's documentation without any luck.

HTML code

<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();
 }

Error

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)

Solution

  • you can select the first option and changing its selected prop to true like so:

    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>