I have a input inside of a bootstrap modal. When the modal is opened, I want the input that that is inside the bootstrap modal to be automatically selected.
I have the following code:
$('#modal').on('show.bs.modal', function (e) {
$(this).$("input").select();
})
and my modal looks like:
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<input type='text' disabled value="test">
</div>
</div>
</div>
</div>
Unfortunately, with this code, I'm getting the error "Uncaught TypeError: undefined is not a function "
Use .find() and then .focus()
$('#modal').on('show.bs.modal', function (e) {
var input = $(this).find("input"); // cache the variable
input.removeAttr('disabled'); // enable it first, so it can get focus
input.focus(); // focus it
})
and then use .focus() to focus the element. There is nothing called .select() in jQuery core.
what worked for me:
$('#modal').on('shown.bs.modal', function (e) {
$('#modal input[type="text"]')[0].select();
});
note the use of .on('shown.bs.modal'), not .on('show.bs.modal')
try
$('#modal').on('show.bs.modal', function (e) {
var input= $(this).find("input");
if(input){
input.removeAttr('disabled');
input.focus();
}
})
Related
So I've got a function to close a modal when clicking anywhere outside of it.
This is the code:
var modal = document.getElementById('quickViewModal');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
$('.item').removeClass('modal-carousel-fix');
$('.modal-backdrop').css('display','none')
$('.quickview-modal').css('display','none');
$(this).parent().closest('.carousel-inner').css('overflow', 'hidden');
}
}
The html looks something like this
<div class="modal quickview-modal" id="quickViewModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<p>Modal Content</p>
</div>
</div>
</div>
</div>
However, when I change my JS to get the modal by class name instead it stops working.
This is the code:
var modal = document.getElementsByClassName('quickview-modal');
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
$('.item').removeClass('modal-carousel-fix');
$('.modal-backdrop').css('display','none')
$('.quickview-modal').css('display','none');
$(this).parent().closest('.carousel-inner').css('overflow', 'hidden');
}
}
My reason for trying to get the modal by class name instead is that as it's a quickview modal for a product there are several of them, so if I get it by ID the code only works for the first item.
Because you will have an array elements getting by class name, not only 1 element.
I am using bootstrap4 alpha 6 Modal, I am getting:
Error: Modal is transitioning
That happen when I am trying to re-trigger the same modal again with dynamic data through JavaScript function as following:
function openModal(title, text) {
$('.modal-title').text(title);
$('.modal-body p').text(text);
$('#modalAlert').modal('show');
}
I tried to use setTimeout function, but didn't work as in this article:
https://github.com/twbs/bootstrap/issues/21687
Any suggestions?
The quickest solution is to remove the modal 'fade' class which is throwing this error. It seems to be a known issue of the Bootsrap v6 that will be fixed in a next released.
See here
Worked with removing fade from parent div class.
Final Modal code ( Adding here for posterity ) :
HTML
<div class="modal loadingModal" id="applemodal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-body">
<div class="row">
<div class="col-md-6">
</div>
<div class="col-md-6">
<img src="ico/4.svg">
</div>
</div>
</div>
</div>
</div>
JS
$.ajax({
type: "GET",
url: "/getTimeline",
data: {
'dateTime': selected
},
async: true,
beforeSend: function () {
$('#applemodal').modal({
backdrop: 'static',
keyboard: false
});
},
success: function(data) {
$('#applemodal').modal('toggle');
}
});
i am using bootstrap 4 Modal too, My solution;
$(document).on('show.bs.modal', '.modal', function (event) {
var zIndex = 1040 + (10 * $('.modal:visible').length);
$(this).css('z-index', zIndex);
setTimeout(function() {
$('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
}, 0);
});
First open the modal and then try to find the DOM elements that's inside modal (eg. $('.modal-title') and $('.modal-body p'))
Changing the order of executing your function might work:
function openModal(title, text) {
$('#modalAlert').modal('show');
$('.modal-title').text(title);
$('.modal-body p').text(text);
}
Finally, make sure that modal is open/visible in the screen when you access HTML that's inside the modal.
Please set your button type='submit' to type='button'
My solution was to open the model programmatically rather than through the link.
Instead of:
Open My Modal
Use:
Open My Modal
$('#myLink').on('click', function(){
$('#myModal').modal('show');
})
After a blur event on an input field "bootbox1", I want to use a Bootstrap Modal for an message, after the modal closes the focus would go to the input field "bootbox2". But the input field does not get focus.
What am I doing wrong?
Demo
HTML
<input type="text" id="bootbox" />
<input type="text" id="bootbox2" />
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<!-- dialog body -->
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal">×</button>Hello world!</div>
<!-- dialog buttons -->
<div class="modal-footer">
<button type="button" class="btn btn-primary">OK</button>
</div>
</div>
</div>
</div>
JS
$('#bootbox').on('blur', function checkSelection(e) {
$("#myModal").on("show", function () { // wire up the OK button to dismiss the modal when shown
$("#myModal a.btn").on("click", function (e) {
console.log("button pressed"); // just as an example...
$("#myModal").modal('hide');
$('#bootbox2').focus();
// dismiss the dialog
});
});
$("#myModal").on("hide", function () { // remove the event listeners when the dialog is dismissed
$("#myModal a.btn").off("click");
$('#bootbox2').focus();
});
$("#myModal").on("hidden", function () { // remove the actual elements from the DOM when fully hidden
$("#myModal").remove();
});
$("#myModal").modal({ // wire up the actual modal functionality and show the dialog
"backdrop": "static",
"keyboard": true,
"show": true // ensure the modal is shown immediately
});
});
//this works
$('#bootbox2').on('blur', function checkSelection(e) {
$('#bootbox').focus();
});
You need to wait for the hidden.bs.modal event to fire, not the hide.bs.modal.
According to the Bootstrap Docs for the event hide.bs.modal
This event is fired immediately when the hide instance method has been
called.
Whereas hidden.bs.modal
This event is fired when the modal has finished being hidden from the
user (will wait for CSS transitions to complete).
Since your focus is being called before the overlay has been removed the input cannot take the keyboard focus yet.
Bootstrap modal hide is not working. Alert comes in else. but my modal is not hidden Added bootply. My issue is the same one.
<button class="button primary" id="buy" data-toggle="modal" data-target=".bs-example-modal-sm" style= "text-decoration:none;" type="button">Review and confirm</button>
<div class="modal-bootstrap fade bs-example-modal-sm" id="myModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel" aria-hidden="true">
<div class="modal-bootstrap-dialog modal-sm">
<div class="modal-bootstrap-content">
<div class="modal-bootstrap-body">
-- content ----
</div>
</div>
</div>
<div class="modal-bootstrap-footer">
<button type="submit" class="button primary" data-dismiss="modal">Close</button>
<button type="submit" class="button primary">Save changes</button>
</div>
</div>
<script type="text/javascript">
$("#buy").click(function () {
var a = 4;
if (a == 5) {
alert("if");
$('#myModal').modal('show');
}
else {
alert("else");
$('#myModal').modal('hide');
}
});
</script>
bootply
You are using both modal toggling methods: via Javascript and via data attributes. So your click is firing the modal show as your data attributes set, and your Javascript does not affect this trigger.
Just remove the data attributes and go with the Javascript method:
<button class="button primary" id="buy" style="text-decoration:none;" type="button">Review and confirm</button>
<div class="modal-bootstrap fade bs-example-modal-sm" id="myModal" tabindex="-1" role="dialog" aria-labelledby="smallModalLabel" aria-hidden="true">
<!-- modal contents -->
</div>
<script type="text/javascript">
$("#buy").click(function () {
var a = 4;
if (a == 5) {
alert("if");
$('#myModal').modal('show');
} else {
alert("else");
$('#myModal').modal('hide');
}
});
</script>
I had same problem. Remove fade class.
I had the same problem, tried a lot of things but the only solution that worked for me is #Tang Chanrith suggested to remove individually parts of the modal but a little bit improved to place back and the scrollbar. I'll put my answer just if the accepted answer did not work for them. Sorry for my english. Hope I helped.
#Tang Chanrith
Try this function
function hideModal() {
$("#myModal").removeClass("in");
$(".modal-backdrop").remove();
$("#myModal").hide();
}
Improved Sollution
You just have to delete a class from body and css that generated
function hideModal() {
$("#myModal").removeClass("in");
$(".modal-backdrop").remove();
$('body').removeClass('modal-open');
$('body').css('padding-right', '');
$("#myModal").hide();
}
For those still having issues (hi Googlers!), if you're using fade, you'll have to use javascript to remove fade class.
Try this function
function hideModal(){
$("#myModal").removeClass("in");
$(".modal-backdrop").remove();
$("#myModal").hide();
}
Remove the modal class "fade" will do.
I have solution this problem.
$('#landingpage, body').on('click',function(){
$( ".action-close" ).trigger( "click" );});
try to add return false like this:
$("#buy").click(function () {
var a = 4;
if (a == 5) {
alert("if");
$('#myModal').modal('show');
}
else {
alert("else");
$('#myModal').modal('hide');
}
return false;
});
I checked your code.
Now you compare a == 5. but a is always 4. you may have to check this why you are doing this comparison.
Also you need you remove the data-target if you want to open modal from javascript :
<button class="button primary" id="buy" data-toggle="modal" style="text-decoration:none;" type="button">Review and confirm</button>
data-target directly opening the modal.
Check if this is working.
You should try this $('.modal.in').modal('hide')
Via https://github.com/twbs/bootstrap/issues/489
I had the same problem, my mistake was that I was trying to open the modal window a few times. We must test that the modal window is not already open before trying to open it.
if (!($("#MyModal").data('bs.modal') || {})._isShown){
$("#MyModal").modal('show');
}
Hide modal dialog box using bootstrap
Method 1: using bootstrap
$('.close').click();
$("#MyModal .close").click();
$('#myModalAlert').modal('hide');
Method 2: using stop-propagation
$("a.close").on("click", function(e){
$("#modal").modal("hide");
e.stopPropagation();
});
Method 3: After shown method invoke
$('#myModal').on('shown', function () {
$('#myModal').modal('hide');
})
Method 4: Using CSS
this.display='block'; //Set block css
this.display='none'; //set none css after close dialog
In the java script code you need to add one line of code
$("#savechanges").on("click", function (e) {
$("#userModal").modal("hide");
e.stopPropagation(); //This line would take care of it
});
As I encountered, sometimes you need to remove display style:
style="display: block;"
I had the same issue. I tried the JavaScript way suggested in the post, unfortunately it only worked half of the time. If I triggered my modal a few times, it bugs out. As a result I created a work around using CSS:
/* Hide the back drop*/
.modal-backdrop.show {
display: none;
}
/* Simulate the backdrop using background color */
.modal-open .modal {
background-color: rgba(47, 117, 19, 0.3);
}
I was opening the modal popup when I click on the link using data-toggle="modal" attribute which was bound with that link and trying to close it using javascript but I was failed each time, so when I remove the "data-toggle" attribute and "href" from that link and opened it using javascript then it was closing properly using javascript as well.
from the below few lines of code, you can understand easily
Advanced Search
I changed the above link to something link this
Advanced Search
After that when I try to close it using javascript, then I become successful
$("#CustomerAdvancedModal").modal('hide');
I am also having the same problem, where I can't find the correct solution for it.
Later I observed that what is happening when the modal gets closed when it works well.
Three Main properties are,
modal-open class gets removed from <body> tag.
In <body> tag change CSS .
<div> class of modal-backdrop gets removed.
So, When u do these things manually, you will achieve it, when not works.
The code should be as following in Jquery,
$('body').removeClass('modal-open');
$('body').css('padding-right', '');
$(".modal-backdrop").remove();
$('#myModal').hide();
Hence, try this and get a solution.
Before you open a loading modal, make sure that you close all others.
This is the function is use to close the modal:
function hideLoadingModal() {
$('#loadingModal').on('shown.bs.modal', function () {
$('#loadingModal').modal('hide');
});
}
Now if I want to open the modal I call the above function and open a new one after that.
Like this:
hideLoadingModal();
$('#loadingModal').modal('show');
Hope this helps you.
Cheers
One possible reson should be the order of jquery and bootstrap and your script is not in proper sequence.
Below should be the sequence.
1. <script src='js/jquery-3.2.1.min.js'></script>
2. <script src='js/bootstrap.min.js'></script>
3. your own script:
<script type="text/javascript">
$("#buy").click(function () {
var a = 4;
if (a == 5) {
alert("if");
$('#myModal').modal('show');
}
else {
alert("else");
$('#myModal').modal('hide');
}
});
</script>
Check if you closed all nested div inside main modal div
<div data-backdrop="static" class="modal fade" id="modal-progress" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
-----NESTED DIV ------------------
</div>
None of the above solutions worked for me. If this is your case, try to imitate click event on the close button (the one which is added dynamically):
<div class="modal" tabindex="-1" role="dialog" id="modal" area-hidden="true" style="display: inline-block;">
<div class="modal-dialog modal-dialog-centered" role="document">
...
</div>
Close</div>
</div>
$('.close-modal').click() should resolve the issue.
Try this
give an id to close button
<button type="submit" id="modalcloseBtn" class="button primary" data-dismiss="modal" >Close</button>
and trigger onclick event
$('#modalcloseBtn').trigger("click");
G.modals = [];
/**
*
* #param {
* modalId: string,
* callback: function
* } options
* #returns
*/
const openModal = (options) => {
const {
modalId = false,
callback = () => { }
} = options;
if (!modalId) return;
const modalNode = document.querySelector(`#${modalId}`);
modal = new bootstrap.Modal(modalNode);
modal.show();
const modalObject = {
modal,
id: modalId
};
G.modals.push(modalObject);
callback();
};
/**
*
* #param {
* modalId: string,
* callback: function
* } options
* #returns
*/
const closeModal = (options) => {
const {
modalId = false,
callback = () => { }
} = options;
if (!modalId) return;
const currentModal = G.modals.find(item => item.id === modalId) || false;
if(!currentModal) return;
const { modal } = currentModal;
const { _element, _backdrop } = modal;
_element.classList.remove('show');
_backdrop._element.remove();
G.modals.splice(G.modals.indexOf(currentModal), 1);
callback();
};
openModal({
modalId: 'your-modal-id',
callback: () => {
DoSomethingAfterModalOpened();
}
});
closeModal({
modalId: 'your-modal-id',
callback: () => {
DoSomethingAfterModalClosed();
}
});
if nothing helps (that happens) - make sure that nobody prevents it like below (my case):
$modal.on('hide.bs.modal', function (e) {
if (shouldNotBeClosed) {
return e.preventDefault();
}
});
Same issue here for no reason, i'm not using "fade" stuff.
I open modal and close modal only with js, the hide function is working only when called inside a setTimeout.
<script>
var modal_show = function(){
$("#modal_post").modal("show");
};
var modal_hide = function(){
$("#modal_post").modal("hide");
};
window.addEventListener("message", function(event){
// listening iframe post message
modal_hide();
});
</script>
<div class="modal" id="modal_post" tabindex="-1" role="dialog" style="width: 100%;" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog" style="width: 450px; height:600px; background: white; border: none; box-shadow: none;" role="document">
<div class="modal-content" style="width: 100%; background: white; border: none; box-shadow: none;">
<div class="modal-body" style="width: 100%; background: white; border: none; box-shadow: none; padding: 0;">
<div>
<iframe src="https://perdu.com" style="width:450px;height:600px;"></iframe>
</div>
</div>
</div>
</div>
</div>
For no reason, modal_hide(); is working inside the console but not in my code.
If i replace the modal_hide(); in the event listener with setTimeout(modal_hide, 200); it's working properly
its very easy.. Remove fade class :)
How to clear all input fields in a Bootstrap V3 modal when clicking the data-dismiss button?
http://getbootstrap.com/javascript/#modals shows an event for when a modal is hidden. Just tap into that:
$('#modal1').on('hidden.bs.modal', function (e) {
$(this)
.find("input,textarea,select")
.val('')
.end()
.find("input[type=checkbox], input[type=radio]")
.prop("checked", "")
.end();
})
http://jsfiddle.net/5LCSU/
I would suggest the above as it bind the clearing to the modal itself instead of the close button, but I realize this does not address your specific question. You could use the same clearing logic bound to the dismiss buttons:
$('[data-dismiss=modal]').on('click', function (e) {
var $t = $(this),
target = $t[0].href || $t.data("target") || $t.parents('.modal') || [];
$(target)
.find("input,textarea,select")
.val('')
.end()
.find("input[type=checkbox], input[type=radio]")
.prop("checked", "")
.end();
})
http://jsfiddle.net/jFyH2/
There is a more easy and beautiful way:
$('#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).
If you are using a form in the modal then you can use
$("#form_id").trigger("reset");
I did it in the following way.
Give your form element (which is placed inside the modal) anID.
Assign your data-dimiss an ID.
Call the onclick method when data-dimiss is being clicked.
Use the trigger() function on the form element.
I am adding the code example with it.
$(document).ready(function()
{
$('#mod_cls').on('click', function () {
$('#Q_A').trigger("reset");
console.log($('#Q_A'));
})
});
<div class="modal fade " id="myModal2" role="dialog" >
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" ID="mod_cls" data-dismiss="modal">×</button>
<h4 class="modal-title" >Ask a Question</h4>
</div>
<div class="modal-body">
<form role="form" action="" id="Q_A" method="POST">
<div class="form-group">
<label for="Question"></label>
<input type="text" class="form-control" id="question" name="question">
</div>
<div class="form-group">
<label for="sub_name">Subject*</label>
<input type="text" class="form-control" id="sub_name" NAME="sub_name">
</div>
<div class="form-group">
<label for="chapter_name">Chapter*</label>
<input type="text" class="form-control" id="chapter_name" NAME="chapter_name">
</div>
<button type="submit" class="btn btn-default btn-success btn-block"> Post</button>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button><!--initially the visibility of "upload another note" is hidden ,but it becomes visible as soon as one note is uploaded-->
</div>
</div>
</div>
</div>
Hope this will help others as I was struggling with it since a long time.
Put the contents in your modal inside a form and give it an ID which is equal to "myForm".
When the close button is clicked, give an onclick to the function "myFunction()".
<button class="btn btn-default" data-dismiss="modal" onclick="myFunction()">Cancel</button>
function myFunction() {
document.getElementById("myForm").reset();
}
$('[data-dismiss=modal]').on('click', function (e)
{
var $t = $(this),
target = $t[0].href || $t.data("target") || $t.parents('#myModal') || [];
$(target)
.find("input")
.val('')
.end()
.find("input[type=checkbox]")
.prop("checked", " ")
.end();
$("span.inerror").html(' ');
$("span.inerror").removeClass("inerror");
document.getElementById("errorDiv1").innerHTML=" ";
})
This code can be used on close(data-dismiss)of modal.(to clear all fields)
Here I have cleared my input fields and my div as id="errorDiv1" which holds all validation errors.
With this code I can also clear other validation errors having class as inerror which is specified in span tag with class inerror
and which was not possible using document.getElementsByClassName
This is helpfull, its work for me..
$('.bd-example-modal-sm').on('hidden.bs.modal', function () {
$(this).find("select").val('').end(); // Clear dropdown content
$("ul").empty(); // Clear li content
});
The following worked for me:
$(':input').val('');
However, it is submitting the form, so it might not be what you are looking for.
In addition to #Malk, I wanted to clear all fields in the popup, except the hidden fields.
To do that just use this:
$('.modal').on('hidden.bs.modal', function () {
$(this)
.find("input:not([type=hidden]),textarea,select")
.val('')
.end()
.find("input[type=checkbox], input[type=radio]")
.prop("checked", "")
.end();
});
This will clear all fields, except the hidden ones.
enclose your modal body inside a form with an id="myform"
and then
$("#activatesimModal").on("hidden.bs.modal",function(){
myform.reset();
});
should do the trick