Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call back function in modal of bootstrap3

Im a little bit confuse about firing a call back function in javascript modal of bootstrap3. In normal jquery.post you can do it like,

$.post('path', { something: something }, function(data) {    console.log(data); }); 

But in bootstrap 3 modal I fires the modal through script and I do it like this base on how I understand the explanation in their website.

$('selector').modal('show', function() {    //here comes the problem, I have a button in the modal in the html, my code   //if the button was clicked inside this modal is..    $('#myButton').on('click', function() {       console.log("this is a try");   }); }); 

But sad to say if I click the button, nothing is happening, nothing was logged in the console. How do I call a callback function in a modal of bootstrap 3?

like image 456
HTTP Avatar asked Oct 30 '13 07:10

HTTP


People also ask

How do you call a function in modal open?

you can use show instead of shown for making the function to load just before modal open, instead of after modal open. $('#code'). on('show.

How to use modal in Bootstrap?

To trigger the modal window, you need to use a button or a link. Then include the two data-* attributes: data-toggle="modal" opens the modal window. data-target="#myModal" points to the id of the modal.

What is modal Bootstrap?

Modals are built with HTML, CSS, and JavaScript. They're positioned over everything else in the document and remove scroll from the <body> so that modal content scrolls instead. Clicking on the modal “backdrop” will automatically close the modal. Bootstrap only supports one modal window at a time.


2 Answers

For Bootstrap 3, the events are now namespaced, so the show event for the modal would be show.bs.modal...

$('#myModal').on('show.bs.modal', function (e) {     alert('modal show'); }); 

Demo: http://bootply.com/90952

like image 158
Zim Avatar answered Sep 30 '22 14:09

Zim


@Skelly is right, you can use the show.bs.modal event like this:

$('#myModal').on('show.bs.modal', function (e) {     alert('modal show'); }); 

The official documentation says:

This event fires immediately when the show instance method is called.

Please note that this event is fired "quite soon" and you may need to use shown.bs.modal instead.

Documentation about this event:

This event is fired when the modal has been made visible to the user (will wait for CSS transitions to complete).

This impacts @Keith yeoh's answer and you should avoid timeouts when possible.

Source: Official Bootstrap documentation

like image 31
mpsq Avatar answered Sep 30 '22 15:09

mpsq