Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap modal onload event

Does a bootstrap modal have an onload event? I want to call a http GET request when the modal is opened to populate the modal with data from a rest api. I have a form in the modal and I have called the GET function on the onload event of the form, but it doesn't work.

<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-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">Agent details:</h4>
      </div>
      <div class="modal-body">

<form onload="getData()" style= "font-size: 16pt">
like image 771
bookthief Avatar asked Nov 21 '13 14:11

bookthief


People also ask

How do I open modal onload?

Answer: Use the Bootstrap . modal('show') method modal('show') method for launching the modal window automatically when page load without clicking anything. A common example of this technique is loading the modal when user landed on the home page and requesting them to subscribe the website newsletter.

How do you trigger modals?

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.


2 Answers

Per the documentation, you can listen to the show or shown events.

From The Documentation:

show.bs.modal => This event fires immediately when the show instance method is called.

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

$('#myModal').on('show.bs.modal', function () {
  // do something…
})
like image 157
Dmase05 Avatar answered Oct 14 '22 04:10

Dmase05


What I've found to be the best way to do this is to add the onclick attribute to the html element that calls the modal.

<button type="button" onclick="PopulateAddModal()" class="btn btn-sm btn-primary" data-toggle="modal" data-target="#AddModal">Add</button>

Then in your javascript..

    function PopulateAddModal() {
      //do stuff here...
      }

This will ensure that your code is ran as soon as the modal is called. Otherwise, the javascript code will not run until the modal has completely finished it's "fade-in" animation.

like image 34
lbecker34 Avatar answered Oct 14 '22 05:10

lbecker34