I have multiple bootstrap modal in my application and I want to call an same function on each modal shown.bs.modal
event. I want to do this globally at one place but the thing that bother me is that this event needs an id
attribute of a particular modal like below:
$('#myModal').on('shown.bs.modal', function () {
$('#myInput').focus()
})
I want to know that is there any way to do it globally as whenever some modal shows, then one function call?
I have multiple bootstrap modal in my application and I want to call an same function on each modal shown.bs.modal
event. I want to do this globally at one place but the thing that bother me is that this event needs an id
attribute of a particular modal like below:
$('#myModal').on('shown.bs.modal', function () {
$('#myInput').focus()
})
I want to know that is there any way to do it globally as whenever some modal shows, then one function call?
Share Improve this question edited Jan 15, 2016 at 6:47 Shashank Agrawal 25.8k11 gold badges96 silver badges125 bronze badges asked Jan 15, 2016 at 6:33 Umer WaheedUmer Waheed 4,6047 gold badges45 silver badges68 bronze badges 2- 1 consider using a class name instead of id – Abdul Rehman Sayed Commented Jan 15, 2016 at 6:36
- 1 Call using the class .modal because that es for all modal – Adarsh Mohan Commented Jan 15, 2016 at 6:55
5 Answers
Reset to default 3$('#myModal')
is simply a jQuery selector. Read more about the jQuery selectors. We can write anything withing $()
like:
$("#myModal") // Select an element with id "myModal"
$("body > #myModal") // Select an element with id "myModal" which is a immediate child of the "body" tag
$("#foo .modal") // Select all elements with a class "modal" which is inside an element with id "foo"
So, in Bootstrap, every modal has a class .modal
, you can simply use that class to attach a global listener:
$('.modal').on('shown.bs.modal', function () {
$('#myInput').focus()
});
Or, like others have mentioned, you can give a class to all your modal where you want to do some mon stuff like do-mon-stuff
:
<div class="modal do-mon-stuff" id="foo">...</div>
<div class="modal" id="bar">...</div>
<div class="modal do-mon-stuff" id="tango">...</div>
and later,
$('.do-mon-stuff').on('shown.bs.modal', function () {
$('#myInput').focus()
});
You can go with the Class name of model
$('.modelClassName').on('shown.bs.modal', function () {
$('#myInput').focus()
})
Try it with class
$('.classNameOfModal').on('shown.bs.modal', function () {
$('#myInput').focus()
})
Consider accessing through class name. Dot '.' is used for class.
$('.myModal').on('shown.bs.modal', function () {
$('#myInput').focus()
})
This is working great for me.
$(window).on("shown.bs.modal", function () {
//Do what ever you want here...
});