I'm kind of stuck at the moment. Would really appreciate if someone can help me with this.
First time asking a question, so please bear with me :)
I have a main page with a few buttons. Each button opens a bootstrap modal. I am able to load dynamic content into the modal. Also inserting external HTML works, but here's the catch.... The HTML content I insert also has some 'fancy' features like my main page has (ex. animated progress bar/skills) For the external HTML to work I need to reference the same script as my main page has, but if so, things on my main page gets broken.
My question is, is there any way that I can insert HTML into my modal and have the inserted HTML be able to use the existing functions on my main page?
var iModal = document.getElementById('iModal');
iModal.addEventListener('show.bs.modal', function handler() {
// Button that triggered the modal
var button = event.relatedTarget;
var modalTitleArg = button.getAttribute('data-bs-title');
var modalId = button.getAttribute('data-bs-id');
var modalTitle = iModal.querySelector('.modal-title');
var modalBody = iModal.querySelector('.modal-body');
modalTitle.textContent = modalTitleArg;
if (modalId == 1) {
$('.modal-body').load('Content1.html', function() {
$.getScript("js/functions.js") //get script, modal works, broken mainpage.
});
} else if (modalId == 2) {
$('.modal-body').load('Content2.html', function() {
//$.getScript("js/functions.js") //script reference in html, modal works broken mainpage
});
} else {
$('.modal-body').load('Content3.html', function() {
//$.getScript("js/functions.js") // no script at all, broken modal, mainpage works fine
});
}
this.removeEventListener('show.bs.modal', handler);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn btn-outline-light mt-2" data-bs-toggle="modal" data-bs-target="#iModal" data-bs-id="1" data-bs-title="Title1">Click me 1</button>
<button type="button" class="btn btn-outline-light mt-2" data-bs-toggle="modal" data-bs-target="#iModal" data-bs-id="2" data-bs-title="Title2">Click me 2</button>
<button type="button" class="btn btn-outline-light mt-2" data-bs-toggle="modal" data-bs-target="#iModal" data-bs-id="3" data-bs-title="Title3">Click me 3</button>
<!-- modal -->
<div class="modal fade" id="iModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="myModalLabel">Title</h3>
<!-- data-bs-title -->
<button type="button" class="btn-close btn-sm" data-bs-dismiss="modal" aria-hidden="true"></button>
</div>
<div class="modal-body">
<!-- external html content -->
</div>
<div class="modal-footer">
<button type="button" class="btn-close btn-sm" data-bs-dismiss="modal" aria-hidden="true"></button>
</div>
</div>
</div>
</div>
<script src="js/functions.js"></script>
If in your "Content1.html", "Content2.html" etc. there is already an attached <script src="js/functions.js"></script> (as in a simple web page), then you can add content simply through an iframe tag (via the src attribute). Sample part of the code from your example:
...
<div class="modal-body">
<iframe class="modal-body-frame"></iframe>
</div>
...
<script>
...
const modalFrame = document.querySelector('.modal-body-frame');
if (modalId === 1) modalFrame.src = 'Content1.html';
...
</script>
...
But if you need to embed the script into the content every time, then you can use the srcdoc attribute of the iframe tag. Example below:
...
<div class="modal-body">
<iframe class="modal-body-frame" srcdoc=""></iframe>
</div>
...
<script>
...
const modalFrame = document.querySelector('.modal-body-frame');
if (modalId === 1) {
$.get('Content1.html', function(data) {
modalFrame.srcdoc = data.replace('</head>', '<script src="js/functions.js"></script></head>');
})
}
...
</script>
...
When using frame, it is important not to forget about Feature Policy and the ability to add permission via the allow attribute (Example: <iframe srcdoc="<p>Example test page</p>" allow="fullscreen"></iframe>).
I have this modal
<form id="contactModal">
<div id="mymodal2" class="" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<span class="modal-title th2" id="lblModalLabel" name="lblModalLabel">Contact</span>
</div>
<div class="modal-body">
What I want is to clear modal every time its closed so I wrote a script like this:
function clear() {
$("#txtNombreCompleto").val("");
$("#txtNombreEmpresa").val("");
$("#exampleInputEmail2").val("");
$("#dropOficina").val("");
$("#txtTelefono").val("");
$("#txtMensaje").val("");
}
$('#mymodal').on('hidden', function(){
$.clear(this)
});
So my inputs inside the modal are something like this:
<input type="text" class="form-control" id="txtNombreCompleto" name="txtNombreCompleto" placeholder="Nombre completo">
But when I close the modal, it doesn´t run the function, how can I run the function when the modal closes? Regards
Simply call clear(); inside bootstrap modal hide.bs.modal event(or hidden.bs.modal) handler or set the function as callback. Also put your code inside document ready handler for attaching event handler after loading the page.
$(document).ready(function() {
$('#mymodal').on('hidden', function() {
clear()
});
});
or get all form all elements inside modal and set value
$(document).ready(function() {
$('#mymodal').on('hidden', function() {
$(':input', this).val('');
});
});
I tried this code in my project but it didn't work. So I tried this new code
$(document).ready(function() {
$('.modal').on('hidden.bs.modal', function(){
$(this).find('form')[0].reset();
});
});
$('.btnLogMesaj').click(function () { // your button is clicked
$('div#demo').empty(); // clear the "div" of the id "demo"
*
*
*
});
<div class="modal-body">
<div id="demo">
<h4>... Merve's contents </h4>
</div>
</div>
I have a list box in the bootstrap modal and a button.
When the button is clicked a new button gets rendered inside a div in the modal.
When I close the modal and reopen it, the last operation performed on the modal like the button rendered earlier is still present in the modal.
How do reset the modal so that when the modal is opened again, the button is not present and user can again select the option from the list box and click on the button to render a new button and so on.
<!-- Modal -->
<div
class="modal fade"
id="myModal"
tabindex="-1"
role="dialog"
aria-labelledby="myModalLabel"
aria-hidden="true"
>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span
><span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Select Language</h4>
</div>
<div class="modal-body">
<button type="button" class="btn" data-dismiss="modal">Close</button>
<button type="button" class="btn" id="submit_form">Submit</button>
<div class="modal-body1">
<div id="placeholder-div1"></div>
</div>
</div>
<div class="modal-footer">
<script>
$("#submit_form").on("click", function () {
$(".modal-body1").html("<h3>test</h3>");
});
</script>
<script>
$(function () {
$(".modal-footer").click(function () {
$(".modal").modal("hide");
});
});
</script>
</div>
</div>
</div>
</div>
-- Update ---
Why doesn't this work?
<script type="text/javascript">
$(function () {
$("#myModal").on("hidden.bs.modal", function (e) {
console.log("Modal hidden");
$("#placeholder-div1").html("");
});
});
</script>
Just reset any content manually when modal is hidden:
$(".modal").on("hidden.bs.modal", function(){
$(".modal-body1").html("");
});
There is more events. More about them here
$(document).ready(function() {
$(".modal").on("hidden.bs.modal", function() {
$(".modal-body1").html("Where did he go?!?!?!");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch modal
</button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<div class='modal-body1'>
<h3>Close and open, I will be gone!</h3>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Tried it and working well
$('#MyModal').on('hidden.bs.modal', function () {
$(this).find('form').trigger('reset');
})
reset is dom build-in funtion, you can also use $(this).find('form')[0].reset();
And Bootstrap's modal class exposes a few events for hooking into modal functionality, detail at here.
hide.bs.modal This event is fired immediately when the hide instance
method has been called.
hidden.bs.modal This event is fired when the modal has finished being
hidden from the user (will wait for CSS transitions to complete).
What helped for me, was to put the following line in the ready function:
$(document).ready(function()
{
..
...
// codes works on all bootstrap modal windows in application
$('.modal').on('hidden.bs.modal', function(e)
{
$(this).removeData();
}) ;
...
..
});
When a modal window is closed and opened again, the previous entered and selected values, will be reset to the initial values.
I hope this will help you as well!
Try cloning, then removing and re-adding the element when the modal is hidden. This should keep all events, though I haven't thoroughly tested this with all versions of everything.
var originalModal = $('#myModal').clone();
$(document).on('#myModal', 'hidden.bs.modal', function () {
$('#myModal').remove();
var myClone = originalModal.clone();
$('body').append(myClone);
});
To reset all the input fields in a modal use the following.
$(".modal-body input").val("")
Here's an alternative solution.
If you're doing a lot of changes to the DOM (add/removing elements and classes), there could be several things that need to be "reset." Rather than clearing each element when the modal closes, you could reset the entire modal everytime it's reopened.
Sample code:
(function(){
var template = null
$('.modal').on('show.bs.modal', function (event) {
if (template == null) {
template = $(this).html()
} else {
$(this).html(template)
}
// other initialization here, if you want to
})
})()
You can still write your initial state in HTML without worrying too much about what will happen to it later. You can write your UI JS code without worrying about having to clean up later. Each time the modal is relaunched it will be reset to the exact same state it was in the first time.
Edit: Here's a version that should handle multiple modals (I haven't tested it)...
(function(){
$('.modal').on('show.bs.modal', function (event) {
if (!$(this).data('template')) {
$(this).data('template', $(this).html())
} else {
$(this).html($this.data('template'))
}
// other initialization here, if you want to
})
})()
(function(){
$(".modal").on("hidden.bs.modal", function(){
$(this).removeData();
});
});
This is perfect solution to remove contact while hide/close bootstrap modal.
That's works for me accurately
let template = null;
$('.modal').on('show.bs.modal', function(event) {
template = $(this).html();
});
$('.modal').on('hidden.bs.modal', function(e) {
$(this).html(template);
});
also, you can clone your modal before open ;)
$('#myModal')
.clone()
.modal()
.on('hidden.bs.modal', function(e) {
$(this).remove();
});
Reset form elements ( Works with bootstrap 5 as well). Sample code :
$(document).on("hidden.bs.modal", "#modalid", function () {
$(this).find('#form')[0].reset();
});
you can try this
$('body').on('hidden.bs.modal', '.modal', function () {
$(this).removeData('bs.modal');
});
It will remove all the data from the model and reset it.
I am using BS 3.3.7 and i have a problem when i open a modal then close it, the modal contents keep on the client side no html("") no clear at all. So i used this to remove completely the code inside the modal div.
Well, you may ask why the padding-right code, in chrome for windows when open a modal from another modal and close this second modal the stays with a 17px padding right.
Hope it helps...
$(document)
.on('shown.bs.modal', '.modal', function () {
$(document.body).addClass('modal-open')
})
.on('hidden.bs.modal', '.modal', function () {
$(document.body).removeClass('modal-open')
$(document.body).css("padding-right", "0px");
$(this).removeData('bs.modal').find(".modal-dialog").empty();
})
Sample code:
$(document).on('hide.bs.modal', '#basicModal', function (e) {
$('#basicModal').empty();
});
The below statements show how to open/reopen Modal without using bootstrap.
Add two classes in css
And then use the below jQuery to reopen the modal if it is closed.
.hide_block
{
display:none !important;
}
.display_block
{
display:block !important;
}
$("#Modal").removeClass('hide_block');
$("#Modal").addClass('display_block');
$("Modal").show("slow");
It worked fine for me :)
Using BS 3.3.7
$("#yourModal").on('hidden.bs.modal', function () {
$(this).data('bs.modal', null); // will clear all element inside modal
});
/* this will change the HTML content with the new HTML that you want to update in your modal without too many resets... */
var = ""; //HTML to be changed
$(".classbuttonClicked").click(function() {
$('#ModalDivToChange').html(var);
$('#myModal').modal('show');
});
Reset form inside the modal. Sample Code:
$('#myModal').on('hide.bs.modal', '#myModal', function (e) {
$('#myModal form')[0].reset();
});
To reset/clear all input fields from bootstrap modal use the following code:
$(".modal-body input").val("")
To hide/close bootstrap modal use the following code:
$('#yourModalId').modal('hide');
Keep Coding 😎
I been scratching my head on this one for a while.
Writing a plugin in grails that calls on bootstrap-mini.js and most of its css. Everything works fine. The issue I am having is I have a remote form which onComplete runs java script:
https://github.com/vahidhedayati/ml-test/blob/master/grails-app/views/mailingListModal/_modalcreate.gsp
<g:javascript>
function ${controller}CloseModal() {
var myClone=$('#BuildModal${id}').clone();
$('#BuildModal${id}').dialog().dialog('close');
$(".modal-backdrop").hide();
$('body').removeClass('modal-open');
//var myCloner = myClone.clone();
$('#${divId}1').hide().append(myClone);
//$('body').append(myClone);
<g:if test="${!disablecheck.equals('true') }">
var controller="${controller }";
var divId="${divId }";
$.get('${createLink(controller:"MailingListEmail", action: "getAjaxCall")}?ccontroller='+controller+'&divId='+divId,function(data){
$('#${divId}').hide().html(data).fadeIn('slow');
});
</g:if>
}
</g:javascript>
The bits at the top of the function is all the things I have tried so far.
https://github.com/vahidhedayati/ml-test/blob/master/grails-app/views/mailingListEmail/contactclients.gsp
<div class="tbutton">
<button href="#BuildModalSENDERS" class="btn btn-block btn-success" role="button" data-toggle="modal" title="Configure New Sender">
New Sender?</button>
<div id="mailerSenders1">
<g:render template="/mailingListModal/modalcreate" model="[title:'Add Senders Email', controller: 'mailingListSenders', callPage: 'form' , divId: 'mailerSenders', id: 'SENDERS' ]" />
</div>
And finally modelForm which is included on the top of the modalcreate.gsp (now shown)
<div class="modal fade" id="BuildModal${id}" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<g:if test="${flash.message}">
<div class="message" role="status">${flash.message}</div>
</g:if>
<g:formRemote id="${controller}" name="urlParams" class="form-horizontal" url="[controller:controller, action:'save']"
update="BuildModal${id}" onComplete="${controller}CloseModal()"
>
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">x</button>
<h3>${title }</h3>
</div>
<div class="modal-body">
<div class="form-group">
<g:render template="/${controller }/${callPage }"/>
<g:submitToRemote class="myformsubmit" url="[controller:controller, action:'save']" update="BuildModal${id}" onComplete="${controller}CloseModal()" value="Create" />
</div>
</div>
</g:formRemote>
</div>
</div>
</div>
</div>
So it is a remote Form that submits can calls the above CloseModal
The question is when I Close this how do I make it available again when the user clicks the button to create new email ?
After adding all the cloning at the top of java script the only difference I was able to make was to make it display the backdrop on 2nd click so it went black on 2nd click but did not show up the modal content.
ok got it working by doing this:
<button href="#BuildModalSENDERS" class="btn btn-block btn-success" role="button" data-toggle="modal" title="Configure New Sender"
Now adding
onClick="runCheck()"> .....
<g:javascript>
function runCheck() {
$('#mailerSenders1').show();
}
</g:javascript>
That seems to work fine, it now loads up the page, just to add when I did body it just loaded it up again from the commented out attempts, modal.hide etc did not work and the hide attempts just showed it up under some other layers of the same page.. anyways this works fine now. sorry
I have problem with jquery $.post function. I use this function a lot and same function works fine except in one case and I don't understand why it keeps redirecting me after script was executed, here is js code:
var record;
$('.delbtt').on('click', function(e){
e.preventDefault();
var deleteid = $(this).parent().parent().find('#id').text();
record = $(this).parent().parent();
$('#delrecord').empty().val(deleteid);
});
$(document).on('submit', '#delteform', function() {
var formData = $(this).serialize();
$.post('includes/delete.php',formData,processData);
function processData(data){
record.remove();
};
});
HTML:
<!-- Modal -->
<div class="modal fade" id="deleteFormModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<form id="deleteform" class="form-horizontal" role="form" action="includes/delete.php" method="POST"> <!-- -->
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Delete record</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to delete this person?</p>
</div>
<input type="hidden" id="delrecord" name="delrecord" value="" />
<div class="modal-footer">
<button type="button" class="btn btn-default empty" data-dismiss="modal">Cancel</button>
<button id="delentry" type="submit" class="btn btn-danger">Delete Person</button>
</div>
</form>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
I know that function is executed successfully, because if I put alert("Why is this not working?"); after record.remove();, I can see alert and in background code executed, but instead of staying at the same page it redirects me to 'includes/delete.php'. I tried disabling all other $.post functions that I have in my JS, I tried using $('#deleteform').submit(), I tried putting it outside of my main $(document).ready(function() {}); same results... Always same result it redirects me after function completes instead of staying on a page. Does anybody have idea why am I getting this behavior?
php code:
<?php
include('budgetprop/Initialize.php');
Database::GetInstance()->ConnectToServer($errors);
$record = $_POST['delrecord'];
# CONNECT TO DB
if(Database::GetInstance()->ConnectToServer($errors)){
$insertSQL1 = "DELETE FROM salaries WHERE record_id = '".$record."' ";
$stmt1 = sqlsrv_query(Database::GetInstance()->databaseConnection, $insertSQL1);
# IF THERE IS AN ERROR
if(!$stmt1){
echo "Error, cannot delete record";
}else{
Database::GetInstance()->LastInsertId($stmt1);
}
# IF ALL QUERIES WERE SUCCSESSFUL, COMMIT THE TRANSACTION, OTHERWISE ROLLBACK
if($stmt1 && !$errors){
sqlsrv_commit(Database::GetInstance()->databaseConnection);
# FREE THE STATEMENT
Database::GetInstance()->FreeDBStatement($stmt1);
echo "success";
return true;
}else{
sqlsrv_rollback(Database::GetInstance()->databaseConnection);
# FREE THE STATEMENT
Database::GetInstance()->FreeDBStatement($stmt1);
return false;
}
# NO CONNECTION WAS MADE
}else{
return false;
};
?>
preventDefault() doesn't work either
It sounds like your form is still being submitted, hence the redirect. You can stop it with preventDefault()...
$(document).on('submit', '#deleteform', function(e) {
e.preventDefault();
var formData = $(this).serialize();
$.post('includes/delete.php',formData,processData);
function processData(data){
record.remove();
};
});
Assuming "deleteform" is the ID of a form element on your page, within which you have an input or button of type "submit", I would suggest changing the delentry button to have a type of "button".
Most browsers will perform a POST/GET on a form that has an input or button of type submit when that button is clicked.
I would then update your jQuery event handler to select the button and specify an onclick event:
$('#delentry').click(function() {
...
});
If you wish to maintain some form of graceful degradation, you could leave the markup as a submit type button and on $(document).ready(), update the type of the button to be "button".