Bootstrap modal not closing after form submission - javascript

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

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....
})

CKEditor is not working with bootstrap modal

I want to show ckEditor on bootstrap modal but the ckEditor is not opening as shown below. After searching through the internet I have got some solution in a different way like this link but I will perform an ajax request hence I have to open the modal using $('.cia_modal').modal('toggle'). The above-mentioned solution link does not work for me
Modal Button:
<button class="btn btn-info btn-xs cia_modal_btn" data-id="<?php echo $post->post_id; ?>" data-table="post" data-attr="post_id">
Create New Post
</button>
Modal:
<!--Modal-->
<div class="modal fade cia_modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-primary">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title">Create New Post</h4>
</div>
<div class="modal-body">
<form action="/action_page.php">
<div class="form-group">
<textarea class="ck_editor" name="post" id="" cols="30" rows="10"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!--End Modal-->
Javascript:
<script type="text/javascript">
$(document).on("click", ".modal_btn", function (e) {
e.preventDefault();
e.stopPropagation();
let cia_modal = $('.cia_modal');
//Set modal show/hide
cia_modal.modal('toggle');
let id = $(this).attr('data-id');
let table = $(this).attr('data-table');
let attr = $(this).attr('data-attr');
//Set Form Data
let formData = new FormData();
formData.append('id',id);
formData.append('table',table);
formData.append('attr',attr);
$.ajax({
type: 'post',
url: '<?php echo base_url()?>post/create_post',
data: formData,
contentType: false,
processData: false,
success: function (data) {
//
}
});
});
</script>
Please help me. Thanks
I assume, you are using CKEditor 4.x.
You need to create editor using CKEDITOR.replace( 'ck_editor' ), you can do it only on element that is existing inside document. It doesn't matter if it's hidden or not. If your modal is inside DOM, but hidden, then just initialize editor. Otherwise you need to wait until element is appended then call CKEDITOR.replace.
Depending on how bootstraps implements modal.show. If it's just changes CSS to make it visible, then most likely you can initialize editor at the start of your script, if it adds elements to document, then you need to use some of bootstrap events to create editor in right time. See shown.bs.modal: https://getbootstrap.com/docs/4.0/components/modal/#events
Just initialize the editor:
<script type="text/javascript">
ClassicEditor.create($('.ck_editor')[0])
.then( editor => {
console.log( editor );
})
.catch( error => {
console.log( error );
});
$(document).on("click", ".modal_btn", function (e) {
//....

Javascript waiting result of modal

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
});

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 to make JS wait for confirmation modal

This might be really stupid but I am not seeing anything straight here, help me out please.
so their is this guy :
As you can see upon click the function changeBlock is called
this.changeBlock = function() {
var flag = confirm("You sure you want to block this user ?");
if(flag){
blockUser(this.postId);
if(this.block() != ""){
this.block("Blocked");
this.pointId(AS.currentUserDetails.name);
return "Blocked";}
}
}
and somewhere lie the function blockUser
function blockUser(post_id) {
var blockUser = AS.baseUrl + "blockNewUser";
$.ajax({
url:blockUser,
type:"POST",
data:{postId : post_id},
success:function(data) {
// `request` seems a very strange name; perhaps `data` or `response`?
},
error: function(){
// You can't use `document.write` after the page has been parsed
}
});
}
My problem is that I cant use confirm() for confirming block or cancel.
I will have to use a html modal which is used through out the website.
If at some point of the execution I add
$('#my-modal').modal('show');
then though the modal appears but rest of the execution takes place without waiting for me to select yes or no.
And if by some magic I manage to make JS wait for selection, How will I know what was selected ?
what should I do ?
I cannot use any third party modals.
here is the modal I want to use :
<div id="block-confirm-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-body">
<div class="clearfix side-space">
<h3 class="modal-title text-center">Are you sure you want to Block this user ?</h3>
</div>
<form id="form-block-confirm" name="" method="post" action="" class="form-horizontal">
<div class="clearfix side-space">
<div class="clearix text-center">
<button type="submit" class="btn btn-saffron btn-introduce" id='block-confirm-button'>Block</button>
<button type="submit" class="btn btn-saffron btn-introduce" id='block-cancel-button'>Cancel</button>
<!--input type="submit" name="submit" class="btn btn-saffron btn-introduce" value="Post"-->
</div>
</div>
</form>
</div>
</div>
</div>
</div>
you should be doing something like this in such situations .
In View Model:
this.changeBlock = function() {
$('#my-modal').modal('show');
}
function blockUser(post_id) {
//code here
}
this.Block=function(){
blockUser(this.postId);
if(this.block() != ""){
this.block("Blocked");
this.pointId(AS.currentUserDetails.name);
return "Blocked";}
}
}
this.Cancel=function(){
$('#my-modal').modal('hide'); //hide or close what ever suits
}
View :
<button id='block-confirm-button' data-bind="click:Blocked">Block</button>
<button id='block-cancel-button' data-bind="click:Cancel">Cancel</button>
Any issues on this lets us know

Categories

Resources