I am having an issue while trying to create a Materialize select input field dynamically using jQuery. My goal is to append a div with a select field when a button is clicked. Here is my current code:
$(document).ready(function(){
$('select').formSelect();
});
$("#addSelect").click(function(){
$("#addSelect").addClass("disabled");
$("#addSelect").hide();
$("#newContent").append("<div class='row'><div class='input-field col s12'><select> <option value='' disabled selected>Choose your option</option><option value='1'>Option 1</option><option value='2'>Option 2</option><option value='3'>Option 3</option> </select><label>Materialize Select</label><label>Materialize Select</label></div></div><button class='waves-effect waves-light bg-blue btn right' type='button'>Go</button>");
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<div class="container">
<div id='newContent'></div>
<br>
<button class="waves-effect waves-light bg-blue btn right" id="addSelect">Add Select</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
It adds all the html for the select when I inspect the element, however the select doesn't work. Maybe it's a css issue?
Thanks for any help!
The problem is that you are running your $("select").formSelect()
function before your dynamically added select box is appended to the DOM.
This can be fixed by explicitly calling .formSelect()
on the newly added element:
$("#addSelect").click(function(){
$("#addSelect").addClass("disabled");
$("#addSelect").hide();
$("#newContent").append("<div class='row'><div class='input-field col s12'><select> <option value='' disabled selected>Choose your option</option><option value='1'>Option 1</option><option value='2'>Option 2</option><option value='3'>Option 3</option> </select><label>Materialize Select</label><label>Materialize Select</label></div></div><button class='waves-effect waves-light bg-blue btn right' type='button'>Go</button>")
// Find the newly added element and call formSelect() on it.
.find("select").formSelect();
});
Working example: https://codepen.io/sdflkjgnsdlfn/pen/pKZKOr
There are some CSS issues but this should get you going!