Post a form to a popup window with Javascript and jQueryPost a form to a popup window with Javascript and jQuery

Posted November 20th, 2009 in Javascript

I recently needed to post an HTML form into a popup window instead of targeted to the current document or an existing window. The Javascript for doing this is very simple and in this post I show how to post the form into a popup window with regular Javascript and then with jQuery.

With regular Javascript

The Javascript window.open function normally takes a URL as the first parameter, but it can be left blank to open an empty window. The second parameter is the popup window's name and it can be used to target the form into that window.

Using regular Javascript, assign an onsubmit event handler to the form to call a function which pops open a new window when the form is submitted and targets the form to that window. This is illustrated by the example HTML and Javascript code below.

HTML:

<form action="..." method="post" onsubmit="target_popup(this)">
<!-- form fields etc here -->
</form>

Javascript:

function target_popup(form) {
    window.open('', 'formpopup', 'width=400,height=400,resizeable,scrollbars');
    form.target = 'formpopup';
}

With jQuery

The method for opening and targeting the popup window is the same as with the regular Javascript method, but the onsubmit code can be removed from the HTML code and added dynamically after the page has loaded. This keeps the HTML much cleaner.

The HTML form is the same as above, but no longer has a onsubmit handler and has an "id" property so it can be targeted easily by jQuery.

HTML:

<form id="myform" action="..." method="post">
<!-- form fields etc here -->
</form>

Javascript:

$(document).ready(function() {
    $('#myform').submit(function() {
        window.open('', 'formpopup', 'width=400,height=400,resizeable,scrollbars');
        this.target = 'formpopup';
    });
});

Related posts:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus