Saturday, January 23, 2016

JQuery and SP Modal Dialog HTML option



SharePoint SP Modal Dialog accepts either URL or html in the dialog options. The below code snippets show how to create HTML DOM elements using JQuery and pass the container HTML for rendering in the dialog. I chose this option because creating DOM elements with styles and binding them with events using JQuery is easy as compared to plain JavaScript. Using this approach we can create dynamic forms to post/get ajax requests through modal dialogs. 

<script type='text/javascript'>

//Container DIV
var container = $("<div/>").css({
        'width': '80%',
        'margin': '10px 5px 10px 20px',
        'border': '1px solid #808080',
        'padding': '10px 10px 10px 10px'
    });

//Text area for entering comments
var txtcomments = $("<textarea/>",

        { id: 'txtComments', rows: '5', cols: '50' }).css({ 'display': 'block' });


//Button added to DIV
var btn = $("<input/>", { type: 'button', value: 'Save' })
.css({
   'height': '30px',
   'width': '100px',
   'display': 'inline-block',
   'padding-right': '10px'
});

//attach button click event
btn.on("click",

        function () {
        //call ajax or WebMethod and submit data to server
        });

//Spacer DIV
var spacer = $("<div/>").css({ 'height': '30px', 'display': 'block' });

//Append all individual DOM elements to container DIV
container.append(txtcomments)
         .append(btn)
         .append(spacer);

//Dialog options
//key thing is container.get(0) which gives actual DOM element 
var dlgOptions = {
        title: "Form Dialog",
        html: container.get(0), //this is important
        width: 600,
        height: 300,
        dialogReturnValueCallback: function (result, retVal) {  //call back to refresh calling page (parent window)         
            SP.UI.ModalDialog.RefreshPage(SP.UI.DialogResult.OK);
        }
    };

//Once all values are set, on onclick event (client side) of a button call
function onClientButtonClick(){
  SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', dlgOptions);
}
</script>

<!-- HTML Source -->
<!-- this button opens modal dialog -->
<input type='button' onclick='return onClientButtonClick();return false;' value='Open Dialog' style='width:120px' />

References
https://msdn.microsoft.com/en-us/library/office/ff410058(v=office.14).aspx
https://api.jquery.com/get/