Damon Damon - 5 months ago 50x
Javascript Question

Pass data to parent window from modal using Bootstrap

As an example, I have a page that when loads, lists all employees. There is a button on the page that when clicked, initializes a (bootstrap) modal with a form. I populate the form, and click 'Submit'. If the insert was successful, I get the json object back as a response so that I can add the newly created employee to the list - which is behind the modal - without a page refresh.

Everything is working fine. I am getting the json back - and I'm ready to send the data back to the parent window. I knew it would be somewhat tricky, but this SO post gave me hope.


Employee.createEmployee(function (response) {

So far all I'm able to do is get this error back:

Uncaught TypeError: Cannot read property 'document' of null

I am launching the modal via javascript instead of data-attribute in hopes that would allow a better hook back to the parent window:


$('#createemployeebtn').click(function (event) {

No such luck.


Whatever information you can access with your modal can also be added to your page.

$(function() {
  $('#btnLaunch').click(function() {

  $('#btnSave').click(function() {
    var value = $('input').val();
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<button type="button" id="btnLaunch" class="btn btn-primary">Launch Modal</button>

<div class="modal fade" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span>
        <h4 class="modal-title">Modal title</h4>
      <div class="modal-body">
        <p>Enter text:</p>
        <input type="text" id="txtInput">
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" id="btnSave" class="btn btn-primary">Save changes</button>
    <!-- /.modal-content -->
  <!-- /.modal-dialog -->
<!-- /.modal -->

This example pops a modal when a button is clicked. You can then enter text in the input and click the save changes button, and the h1 tag on the page will be set to use that text. You can pop the modal again, change the text in the input field, click the save changes button, and the h1 tag will now display the new text.

This example should illustrate that whatever items are set in the modal can be used to set items on the page that produces that modal. Any element or variable the page has access to, your modal has access to as well.