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:
- 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)
- Calling $(document).ready multiple times with jQuery (Friday, September 11th 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)
Subscribe / Follow / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email to have my posts sent in a daily email, follow me on Twitter or follow me on Facebook.
At least one new post is usually made every day. See my posting schedule for more details.
