I want to create modal in materialize dynamically. this is my javascript code:
$(document).ready(function(){
var modalContainer = $('<div id="modal_id" class="modal"></div>');
var modalContent = $('<div class="modal-content"><p>my content</p></div>');
modalContainer.append(modalContent);
modalContainer.modal(); // or modalContainer.modal('open');
});
and this is my trigger button:
<a class="waves-effect waves-light btn modal-trigger" href="#modal_id">Show Modal</a>
but, this is not working. when i click to Show Modal
anchor, show me the wrapper of modal and do not show modal box.
please help me. thanks.
You can do it with this simple approach. Create and an empty div
with .modal
class and whatever the id
you want to assign.
Then in jQuery, create a variable and save a div
with class modal-content
. In that div
specify your message or content, you want to add dynamically. After that, append that variable to modal using $(.modal).append()
and open your modal using .modal()
Take a look at Example
I've created a jsfiddle
take a look at it.
HTML
<a class="waves-effect waves-light btn modal-trigger" href="#modal1">Modal</a>
<div id="modal1" class="modal"></div>
jQuery
$(document).ready(function(){
// Here specify your content or message, enclose between <p>
var content = '<div class="modal-content"><p>my content</p></div>';
$('.modal').append(content);
$('.modal').modal();
});