Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap modal 'loaded' event on remote fragment

I'm currently using Twitter Bootstrap modal component and i have an issue where I use jquery validation plugin on input fields in the content I load remotely using the data-remote attribute.

Because the content is loaded after jquery validation has run across the dom, validation doesn't occur for the newly loaded elements.

I have a solution where I modify bootstrap.js (the modal class), see below.

  var Modal = function (element, options) {
    this.options = options
    this.$element = $(element)
      .delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this))
    //this.options.remote && this.$element.find('.modal-body').load(this.options.remote)

    this.options.remote && this.$element.find('.modal-body').load(this.options.remote, $.proxy(function () {
        this.$element.trigger('loaded')
    }, this)) //my additions
  }

I trigger a 'loaded' event to the call that loads the external html fragment.

I already have this event wired up and i call the validation on the newly loaded elements.

$('#myModal').on('loaded', function () {
                $.validator.unobtrusive.parse($(this));
            });

My issue is that I had to modify bootstrap.js to achieve this, is there a way I can have this working externally without modifying bootstrap.js? Is there a way to access the modal object on a page and attach the 'loaded' event to it? i'd like to do this in an external script or within a page so i don't need to worry about bootstrap versions.

like image 658
scartag Avatar asked Sep 23 '13 12:09

scartag


3 Answers

Just an update here:

Bootstrap has added a loaded event.

http://getbootstrap.com/javascript/#modals

capture the 'loaded.bs.modal' event on the modal

$('#myModal').on('loaded.bs.modal', function (e) {
  // do cool stuff here all day… no need to change bootstrap
})
like image 60
George Avatar answered Oct 18 '22 20:10

George


The 'loaded.bs.modal' event doesn't work for me, so I have tried the 'shown.bs.modal' event and it's works fine :

$('#myModal').on('shown.bs.modal', function () {
   // do cool stuff here...
});

This event is captured after the modal is shown.

I hope this will help someone :)

like image 19
Mohammed Réda OUASSINI Avatar answered Oct 18 '22 19:10

Mohammed Réda OUASSINI


According to both these issues:

https://github.com/twbs/bootstrap/issues/5169

https://github.com/twbs/bootstrap/pull/6846

..as of now the Bootstrap developers are digging their heels in and refusing to add a loaded event into Bootstrap.

So instead they recommend you avoid using the data-remote markup and load the data yourself into the modal:

$('#myModal').modal(your_options).find('.modal-body').load('request_url', function () {
  // do cool stuff here all day… no need to change bootstrap
}')
like image 18
mccannf Avatar answered Oct 18 '22 20:10

mccannf