Javascript waiting result of modal - javascript

I have a simple question about javascript and bootstrap modal. I have a wizard where I use file upload form, so I check the name of the file and if it doesn't contains some string I have to show a modal where ask if you want to continue anyway. How can I know which button is clicked into modal from javascript or jquery?
I have this code:
if (index==3){
var fileControl = document.getElementById('file');
//Check if the datatable name contains idFLeet and IdCar. REturn -1 if it not contains the string
if (fileControl.files[0].name.indexOf($("#selectedFleet").val()) > -1 && fileControl.files[0].name.indexOf($("#selectedCar").val()) > -1){
//File contains id so you can continue the upload
uploadFunction();
}
else{
$('#warningDatatableModal').modal("show");
//If click on Yes call uploadFunction
//If click on No return false
}
}
HTML modal code:
<div class="modal" id="warningDatatableModal" data-backdrop="static" data-keyboard="false">
<div class="modal modal-warning">
<div class="modal-dialog">
<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">Warning</h4>
</div>
<div class="modal-body">
<p>There is a incongruity between file name and fleet and
car previously selected. Are you sure to continue?</p>
</div>
<div class="modal-footer">
<button id="close" type="button" class="btn btn-outline pull-left"
data-dismiss="modal">Close</button>
<button id="continueButton" type="button" class="btn btn-outline">Continue</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
</div>
After Yeldar Kurmangaliyev advice I have update my code but the wizard go ahed to the next tab instead of waiting into actual tab
if (index==3){
var fileControl = document.getElementById('file');
//Check if the datatable name contains idFLeet and IdCar. REturn -1 if it not contains the string
if (fileControl.files[0].name.indexOf($("#selectedFleet").val()) > -1 && fileControl.files[0].name.indexOf($("#selectedCar").val()) > -1){
//File contains id so you can continue the upload
uploadFunction();
}
else{
$('#warningDatatableModal').modal("show");
$(".modal-footer > button").click(function() {
clicked = $(this).text();
$("#warningDatatableModal").modal('hide');
});
$("#warningDatatableModal").on('hide.bs.modal', function() {
if (clicked === "Cancel"){
return false;
}else {
uploadFunction();
}
});
}
}
If I put this code out of wizard works(it doesn't close modal with cancel button because I use return false that needs for my wizard), but I need to stop wizard waiting modal result.

You can simply attach events to your buttons.
However, the user may want to close the window without action. The design of modal UI and its overlay suggests to click outside the window and close it.
In order to create an event which will fire event always when a user closes your modal, you need to attach to hide.bs.modal event:
$('#warningDatatableModal').on('hide.bs.modal', function() {
});
Here is the working JSFiddle demo.

You can try using the ids of the buttons and attaching a listener to see when they have been clicked like so:
$('#close').on('click',function(){
//do something
});
$('#continueButton').on('click',function(){
//do something
});

Related

AJAX call not triggered on show.bs.modal

I have a button which is supposed to trigger a modal with a contact form. Part of the show.bs.modal function is an AJAX call to my DB to get some file details which are then meant to be shown in the modal-body.
The problem is that the modal does indeed open, but with no modal-body content, which means that the JavaScript code to trigger to the AJAX call is not working. I do not see any network activity in the browser debug menu, no call to the PHP file, and even an alert on top of the JS code telling me that that a button was pressed is not triggered. It seems like the whole JS code is circumvented, yet the modal still shows.
The same code works in another project, anyone has any idea as to why this is happening?
Button:
<div class="card-footer bg-light text-center">
<button id="modal_btn" name="modal_btn" type="button" class="btn bg-teal-400" data-toggle="modal" data-target="#modal_contact_form" data-imgid="'.$row['image_id'].'" data-keyboard="true">
<span class="icon-ico-mail4"></span> Anfragen
</button>
</div>
Modal:
<!-- Contact form modal -->
<div id="modal_contact_form" class="modal fade" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header bg-teal-300">
<h3 class="modal-title">Kaufanfrage - Artikel #1234</h3>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-link" data-dismiss="modal">Abbrechen</button>
<button type="submit" class="btn bg-teal-300">Nachricht Senden</button>
</div>
</form>
</div>
</div>
</div>
<!-- /contact form modal -->
JavaScript:
<script type="text/javascript">
// DISPLAY EDIT RECORD MODAL
$('#modal_contact_form').on('show.bs.modal', function (event) {
//var button = $(event.relatedTarget) // Button that triggered the modal
window.alert("button clicked.");
var imgid = $(event.relatedTarget).data('imgid') // Extract info from data-* attributes
var modal = $(this);
var dataString = 'action=contact&imgid=' + imgid;
$.ajax({
type: "POST",
url: "./assets/ajax/ajax_action.php",
data: dataString,
cache: false,
success: function (data) {
console.log(data);
modal.find('.modal-body').html(data);
},
error: function(err) {
console.log(err);
}
});
});
</script>
try this:
$(document).on('show.bs.modal','#modal_contact_form', function (event) {
// TODO ....
});
Or you can use the onclick button trigger instead of modal show trigger
$("#modal_btn").click(function(event){
// TODO ...
});
Try This
const bsModal = document.querySelector('#exampleModal');
$(bsModal).on('shown.bs.modal', function() {
// YOUR CODE HERE....
})

Bootstrap modal not closing after form submission

I believe I will get a solution here, bootstrap modal does not disappear after form submission. I only want to make bootstrap modal disappear after form submission and when again button is clicked (without refreshing the page) form should open, send data and modal should disappears and so on... This is it !
Here is a bootstrap modal:
<div class="modal fade myPopup" id="basicModal" tabindex="-1" role="dialog"
aria-labelledby="basicModal" aria-hidden="true">
<div class="modal-dialog" id="modal_dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add New Board</h4>
</div>
<div class="modal-body">
<form class="create_Category_board" id="myform">
<input type="text"
id="customInput"
class="board_name"
name="board[name]"
placeholder="Board Name ..." />
<input type="text"
class="board_description"
name="board[description]"
placeholder="Board Description ..." />
<input type="hidden"
class="board_description"
id="myCid"
name="board[category_id]" />
<input type="submit" value="Create Board" class="ShowFormButton"/>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
My form is bound with backbone JS function:
events: {
"submit form.create_Category_board": "createCategoryBoard"
},
createCategoryBoard: function(event) {
event.preventDefault();
var that = this;
// get form attrs, reset form
var $form = $(event.target);
var attrs = $form.serializeJSON();
$form[0].reset();
var board = new Kanban.Models.Board();
// fail if no board name
if (!attrs.board.name) {
var $createContainer = $("div.create_board");
var $nameInput = that.$el.find("input.board_name");
$createContainer.effect("shake", {
distance: 9,
times: 2,
complete: function() {
$nameInput.show();
$nameInput.focus();
}
}, 350);
return false;
}
attrs.board.category_id = myid;
var category = Kanban.categories.get(myid);
var boards = category.get("assigned_boards");
// save list
board.save(attrs.board, {
success: function(data) {
board.get("users").add(Kanban.currentUser);
boards.add(board);
// keep focus on list input
that.$el.find("input.board_name").focus();
}
});
$('#basicModal').modal('hide');
}
As a last line in above function I have tried most popular solution $('#basicModal').modal('hide'); available on web! It makes my modal look like this:
i.e. it not hides the modal, moreover make screen black and change the direction of bootstrap modal from center of screen to little right. May be it is overridden by CSS of JS. But I am not sure.
I am posting my own answer because if some one needs a quicker help, then may be it is helpful:
Just replace: $('#basicModal').modal('hide'); with this line:
$(".modal-header button").click(); which is last line of my JS function.
Cheers :)
Problem is that div.modal-backdrop remains after you hide the modal,
you can see it in developer tools.Try simple remove
$('#basicModal').modal('hide');
$('.modal-backdrop').remove();
Cheers

show bootbox over modal dialog

I have modal dialog like this one
<div id="tenantDialog" class="modal fade" tabindex="-1" data-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">
<i class="fa fa-users"></i>
<spring:message code="label.tenant.person.title"/>
</h4>
</div>
<div class="modal-body">
<%--We load here the persons table here to be reloaded in any moment--%>
<div id="personTableDiv">
<c:set var="preferredCollaborators" value="${preferredCollaborators}" scope="request"/>
<jsp:include page="personsTable.jsp"/>
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
Then in the personsTable.js associate to the include page I have the logic to open a bootbox confirm. But my problem is, that this bootbox it´s showing under the modal dialog, so it´s not intractable.
Here my bootbox creation
bootbox.confirm(customText, function (confirmed) {
if (confirmed) {
var regularityDocumentsIds = [];
var i;
for (i = 0; i < selectedPersons.length; i += 1) {
regularityDocumentsIds.push($(selectedPersons[i]).attr("data-preferredcollaboratorid"));
}
removePersons(regularityDocumentsIds);
}
});
Any idea what can I do to show this bootbox over the modal dialog?
This is a confirmed issue: using bootbox.confirm() within a bootstrap modal.
You have a workaround. Add this in your CSS:
.bootbox.modal {z-index: 9999 !important;}
my humble (working in production) solution
You should edit bootbox, look for the callback of:
dialog.one("hidden.bs.modal", function (e) {
// ensure we don't accidentally intercept hidden events triggered
// by children of the current dialog. We shouldn't anymore now BS
// namespaces its events; but still worth doing
if (e.target === this) {
dialog.remove();
}
});
and change it to:
dialog.one("hidden.bs.modal", function (e) {
// ensure we don't accidentally intercept hidden events triggered
// by children of the current dialog. We shouldn't anymore now BS
// namespaces its events; but still worth doing
if (e.target === this) {
dialog.remove();
}
// inspired by : https://github.com/makeusabrew/bootbox/issues/356#issuecomment-159208242
// if there is another modal, stop the event from propgating to bootstrap.js
// bootstrap.js uses the same event to remove the "modal-open" class from the body, and it creates an unscrolable modals
if ($('.modal.in').css('display') == 'block') {
// do not notify bootstrap about this change!!
e.stopPropagation();
}
});

Get e.relatedTarget when using Twitter Bootstrap modal buttons

I have written the code to show a modal when a button is clicked, with the intention to edit button's text inside the modal.
My intention is to have a lot of buttons, so instead of getting them by id, I use e.relatedTarget when the modal is invoked in order to know which button has called and get the text from the button so I can show it at the modal.
But the problem comes when I edit the text at the modal and click the OK button. I don't know how to access the e.relatedTarget from there.
HTML:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">Change this text</button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<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="exampleModalLabel">New message</h4>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="text-to-edit" class="control-label">Edit text:</label>
<input type="text" class="form-control" id="text-to-edit">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Send message</button>
</div>
</div>
</div>
</div>
JS:
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var buttonText = button.text() // Get text
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-body input').val(buttonText)
});
// Modal ok button
$('#exampleModal .btn-primary').click(function() {
// Get input text value
var text = $('#exampleModal').find('.modal-body input').text();
// Hide modal
$('#exampleModal').modal('hide');
// Set new text to the caller button
// ?
});
JsFiddle: http://jsfiddle.net/nm4nmxsf/
Any help?
I added comments showing you what to change
// Set an empty variable for button outside of your function !important
var button = '';
$('#exampleModal').on('show.bs.modal', function (event) {
//don't redeclare your variable for button, instead update it
button = $(event.relatedTarget) // Button that triggered the modal
var buttonText = button.text() // Get text
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this);
modal.find('.modal-body input').val(buttonText);
});
// Modal ok button
$('#exampleModal .btn-primary').click(function() {
// Get input text value
//use val() instead of text()
var text = $('#exampleModal').find('.modal-body input').val();
$('#exampleModal').modal('hide');
// Set new text to the caller button
// ?
button.text(text);
});
See this fidde:
http://jsfiddle.net/nm4nmxsf/4/
var button;
$('#exampleModal').on('show.bs.modal', function (event) {
button = $(event.relatedTarget);
var buttonText = button.text();
var modal = $(this);
modal.find('.modal-body input').val(buttonText);
});
$('#exampleModal .btn-primary').click(function() {
var text = $('#exampleModal').find('.modal-body input').val();
$('#exampleModal').modal('hide');
button.text(text);
});
JSFIDDLE

How can I trigger a Bootstrap modal programmatically?

If I go here
http://getbootstrap.com/2.3.2/javascript.html#modals
And click 'Launch demo modal' it does the expected thing. I'm using the modal as part of my signup process and there is server side validation involved. If there are problems I want to redirect the user to the same modal with my validation messages displayed. At the moment I can't figure out how to get the modal to display other than a physical click from the user. How can I launch the model programmatically?
In order to manually show the modal pop up you have to do this
$('#myModal').modal('show');
You previously need to initialize it with show: false so it won't show until you manually do it.
$('#myModal').modal({ show: false})
Where myModal is the id of the modal container.
You should't write data-toggle="modal" in the element which triggered the modal (like a button), and you manually can show the modal with:
$('#myModal').modal('show');
and hide with:
$('#myModal').modal('hide');
This is a code for Bootstrap v5 without jQuery.
let myModal = new bootstrap.Modal(document.getElementById('myModal'), {});
myModal.show();
Demo
And this is a codesandbox demo to open modal on page load programmatically.
https://idu6i.csb.app/
Refs
https://getbootstrap.com/docs/5.0/components/modal/#via-javascript
https://getbootstrap.com/docs/5.0/components/modal/#show
If you are looking for a programmatical modal creation, you might love this:
http://nakupanda.github.io/bootstrap3-dialog/
Even though Bootstrap's modal provides a javascript way for modal creation, you still need to write modal's html markups first.
HTML
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg">
Launch demo modal
</button>
<!-- 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" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</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>
JS
$('button').click(function(){
$('#myModal').modal('show');
});
DEMO JSFIDDLE
you can show the model via jquery (javascript)
$('#yourModalID').modal({
show: true
})
Demo: here
or you can just remove the class "hide"
<div class="modal" id="yourModalID">
# modal content
</div>
​
I wanted to do this the angular (2/4) way, here is what I did:
<div [class.show]="visible" [class.in]="visible" class="modal fade" id="confirm-dialog-modal" role="dialog">
..
</div>`
Important things to note:
visible is a variable (boolean) in the component which governs modal's visibility.
show and in are bootstrap classes.
An example component & html
Component
#ViewChild('rsvpModal', { static: false }) rsvpModal: ElementRef;
..
#HostListener('document:keydown.escape', ['$event'])
onEscapeKey(event: KeyboardEvent) {
this.hideRsvpModal();
}
..
hideRsvpModal(event?: Event) {
if (!event || (event.target as Element).classList.contains('modal')) {
this.renderer.setStyle(this.rsvpModal.nativeElement, 'display', 'none');
this.renderer.removeClass(this.rsvpModal.nativeElement, 'show');
this.renderer.addClass(document.body, 'modal-open');
}
}
showRsvpModal() {
this.renderer.setStyle(this.rsvpModal.nativeElement, 'display', 'block');
this.renderer.addClass(this.rsvpModal.nativeElement, 'show');
this.renderer.removeClass(document.body, 'modal-open');
}
Html
<!--S:RSVP-->
<div class="modal fade" #rsvpModal role="dialog" aria-labelledby="niviteRsvpModalTitle" (click)="hideRsvpModal($event)">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="niviteRsvpModalTitle">
</h5>
<button type="button" class="close" (click)="hideRsvpModal()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary bg-white text-dark"
(click)="hideRsvpModal()">Close</button>
</div>
</div>
</div>
</div>
<!--E:RSVP-->
The following code useful to open modal on openModal() function and close on closeModal() :
function openModal() {
$(document).ready(function(){
$("#myModal").modal();
});
}
function closeModal () {
$(document).ready(function(){
$("#myModal").modal('hide');
});
}
/* #myModal is the id of modal popup */
The same thing happened to me. I wanted to open the Bootstrap modal by clicking on the table rows and get more details about each row. I used a trick to do this, Which I call the virtual button! Compatible with the latest version of Bootstrap (v5.0.0-alpha2). It might be useful for others as well.
See this code snippet with preview:
https://gist.github.com/alireza-rezaee/c60da1429c36351ef4f071dec0ea9aba
Summary:
let exampleButton = document.createElement("button");
exampleButton.classList.add("d-none");
document.body.appendChild(exampleButton);
exampleButton.dataset.toggle = "modal";
exampleButton.dataset.target = "#exampleModal";
//AddEventListener to all rows
document.querySelectorAll('#exampleTable tr').forEach(row => {
row.addEventListener('click', e => {
//Set parameteres (clone row dataset)
exampleButton.dataset.whatever = e.target.closest('tr').dataset.whatever;
//Button click simulation
//Now we can use relatedTarget
exampleButton.click();
})
});
All this is to use the relatedTarget property. (See Bootstrap docs)
Here's how you do it with ternary operator
$('#myModal').modal( variable === 'someString' ? 'show' : 'hide');

Categories

Resources