user1432882 user1432882 - 6 months ago 53
jQuery Question

How to dynamically modify <select> in materialize css framework

I just started using the materialize css framework. Now, materialize converts any select tag into a collection of ul and li elements. Before, using JQuery, I was able to do this:

var $selectDropdown = $("#dropdownid");
$selectDropdown.empty();
$selectDropdown.html(' ');
var value = "some value";
$selectDropdown .append($("<option></option>").attr("value",value).text(value));


My html is just a sample select tag:



Before, this was working. Now it fails. What would be an alternative for repopulating this dropdown dynamically using javascript?

Answer

According to the Docs on Materialize Forms:

In addition, you will need a separate call for any dynamically generated select elements your page generates

So the best way is to just re-bind the generated select with an additional call to .material_select().

For re-usability, you can set up a listener when the elements have changed and then trigger that listener whenever you update the original select

// add new option
$selectDropdown.append($("<option></option>"));

// trigger event
$selectDropdown.trigger('contentChanged');

$('select').on('contentChanged', function() {
  // re-initialize (update)
  $(this).material_select();
});

This has the benefit of only needing to update the particular select element that has changed.

Demo in Stack Snippets

$(document).ready(function() {

  // initialize
  $('select').material_select();

  
  $("#myButton").click(function() {
    
    // clear contents
    var $selectDropdown = 
      $("#dropdownid")
        .empty()
        .html(' ');

    // add new value
    var value = "some value";
    $selectDropdown.append(
      $("<option></option>")
        .attr("value",value)
        .text(value)
    );

    // trigger event
    $selectDropdown.trigger('contentChanged');
  });


  $('select').on('contentChanged', function() {
    // re-initialize (update)
    $(this).material_select();
  });
  
});
<link  href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.96.1/css/materialize.min.css" rel="stylesheet">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.96.1/js/materialize.min.js"></script>

<a class="waves-effect waves-light btn" id="myButton">
  Change Dropdown
</a>

<select id="dropdownid" >
  <option>Option 1</option>
  <option>Option 2</option>
  <option>Option 3</option>
</select>