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?
You can reinitialize the select element after your data is bound successfully. Like so,
Similar to this:
It binds its option values to new
ul>li
element by creating the dom object on load.According to the Docs on Materialize Forms:
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
This has the benefit of only needing to update the particular select element that has changed.
Demo in jsFiddle & Stack Snippets:
This works for Materialize 1.0.0-rc.1 :
the situation: I have two fields; first is to select a category
after category is selected, the second select id="subcategory" is populated with good subcats according to the parent category:
This is a valid solution for MaterializeCss v0.96.1. In version 0.97.0 it doesn't work: seems that there is a bug that appends a caret in the HTML.
Here the code for v0.97.0: