Javascript I use to LOAD forms in modals.

67 views
Skip to first unread message

Leonel Câmara

unread,
May 29, 2014, 10:28:40 AM5/29/14
to web...@googlegroups.com
Hey,

I have seen a few people using modals here. So this may be useful to someone.

function load_in_modal(url, modal_id, options) {
    if (typeof options === 'undefined') {
      /* Example Options:
       * {title: "Add Image", upload_form: true}
       */
      options = {};
    }

    /*
     * You can remove this if you don't want to deal with file uploads.
     * If you want to use this, the view/controller using this should
     * insert jquery.form.js on response.files.
     */
    if (Boolean(options.upload_form)) {
        $.web2py.trap_form = function (action, target) {
          /* traps any LOADed form */
          $('#' + target + ' form').each(function (i) {
            var form = $(this);
            if (form.hasClass('no_trap')) {
              return;
            }

            form.attr('data-w2p_target', target);
            var url = form.attr('action');

            if ((url === "") || (url === "#")) {
              /* form has no action. Use component url. */
              url = action;
            }

            if(form.find('.input-file').length>0) {
                form.ajaxForm({
                    url: action,
                    success: function(data, statusText, xhr) {
                        jQuery('#'+target).html(xhr.responseText);
                        $.web2py.trap_form(action,target);
                        $.web2py.ajax_init();
                    }
                });
            }
            else {
                form.submit(function (e) {
                  $.web2py.disableElement(form.find($.web2py.formInputClickSelector));
                  $.web2py.hide_flash();
                  $.web2py.ajax_page('post', url, form.serialize(), target, form);
                  e.preventDefault();
                });
            }
          });
        };
    }
    /* end of file upload dealing code */


    /* Remember to set an id in your modal's body */
    $.web2py.component(url, $('#' + modal_id + ' .modal-body').attr('id'));

    $('#' + modal_id).modal({show: true});
    if (typeof options.title !== undefined) {
        $('#' + modal_id + ' .modal-title').text(options.title);
    }
}


It's pretty self explanatory. You need to have the modal structure already in the HTML remembering to add an id attribute to the modal's body. Then you call load_in_modal usually in a onclick event.
Reply all
Reply to author
Forward
0 new messages