Post 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:
- Write content into a dynamic Javascript popup (Thursday, July 1st 2010)
- Get the number of options in a select with jQuery (Friday, January 15th 2010)
- Javascript: reference the parent window from a popup (Wednesday, November 4th 2009)
- Running a function with jQuery when the window is resized (Tuesday, August 25th 2009)
- Accessing form elements by name with jQuery (Tuesday, June 23rd 2009)
- Opening a new window with Javascript (Saturday, November 22nd 2008)

Comments
blog comments powered by Disqus