user1432882 user1432882 - 9 months ago 86
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.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?


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

// trigger event

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

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

Demo in Stack Snippets

$(document).ready(function() {

  // initialize

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

    // add new value
    var value = "some value";

    // trigger event

  $('select').on('contentChanged', function() {
    // re-initialize (update)
<link  href="" rel="stylesheet">
<script src="//"></script>
<script src=""></script>

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

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