JQuery append () not working inside loading modal
I have a mod to download:
<div class="modal fade" id="container-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" data-backdrop="false">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<ul class="modal_containers" id="list_ctns">
<li><img src="images/container.png"></li>
<li><img src="images/container.png"></li>
<li><img src="images/container.png"></li>
</ul>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
The above modal mode is triggered when a specific button is clicked, which can be seen as a store of specific items.
I have a form that has a submit button. When this submit button is clicked, I want to add a list item to the modal_body.
<div class="button-containers">
<button class="btn btn-success" id="save_item" type="submit">Save</button>
</div>
So, I wrote this simple javascript snippet to add a list item to the modal.
$(document).ready(function(){
$('#save_item').click(function(e){
$("#list_ctns").append("<li><img src="images/container.png"></li>")
});
});
I'm not sure where I am making the mistake. Please help me with your suggestions.
Cheers, SZ
source to share
Pay attention to the quotes when you pass this as a string to set the value.
"<li><img src="images/container.png"></li>"
should be either
"<li><img src='images/container.png'></li>"
or
"<li><img src=\"images/container.png\"></li>"
Also remember to prevent the default action of the submit button.
$('#save_item').click(function(e) {
e.preventDefault();
$("#list_ctns").append("<li><img src='images/container.png'></li>")
});
source to share
The button type is dispatched so when you click on it the form will submit causing the page to redirect to the action url.
You can create a JS function to handle it like this:
function handleModal(form)
{
$("#list_ctns").append("<li><img src=\"images/container.png\"></li>");
//Use $.AJAX() to submit the form without refreshing the page.
return false; //this prevent the form from being submitted. Keep it if you are going to use $.AJAX() to submit the form or remove it if you want the form to submit normally.
}
and then call it from <form>
node by adding an attribute to it onsubmit="return handleModal(this);"
.
source to share