I\'m submitting a form to my rails app, with two submit buttons. They both go to the same controller action, and use the same form, but on one submit action i want to make
In order to handle all submit
cases (not just clicks) I would do something like the following:
$("form").submit(function(e) {
if($(e.srcElement).is(".popup")){
$(this).attr("target", "_blank");
}
});
On one of the buttons, add a class say popup
. Then add some jQuery like this:
$('.popup').click(function(e) {
e.preventDefault(); //prevents the default submit action
$(this).closest('form').attr('target', '_blank').submit();
});
Demo: http://jsfiddle.net/HxrzD/
Note that there are other ways to submit a form that you might need to consider, f.ex the enter
key. You also might need to reset the form’s target attribute in case the user goes back to the parent window and submits again using the other button. In that case you can either just clear the target at the end:
$(this).closest('form').attr('target', '_blank').submit().removeAttr('target');
Or save the previous state:
var $form = $(this).closest('form'),
target = $form.attr('target');
$form.attr('target', '_blank').submit().attr('target', target);
http://jsfiddle.net/HxrzD/2/
you can intercept click to the button, read it's data and change form before submit:
So, HTML:
<form id='double' method="GET" action="http://google.com/search">
<input name="q" type="text">
<button class="Submit" data-target=""> Submmit here</button>
<button class="Submit" data-target="_blank"> Open new</button>
</form>
JS
$('button.Submit').click( function() {
var t=$(this);
var form=t.parents('form');
form.attr('target',t.data('target'));
form.submit();
return false;
});
this way you can control the target option in your html markup.
http://jsfiddle.net/oceog/gArdk/
in case if you not clear target
of the form, you will get the following scenario:
and that will also popup him form target.
so in my snipplet I clear target in case of data-target=''
if you want mark as popup only one element, you will need to clone your form: http://jsfiddle.net/oceog/gArdk/2/
JS:
$('button.Submit.popup').click( function() {
var t=$(this);
var form=t.parents('form').clone(true).attr('target','_blank');
form.submit();
return false;
});
HTML:
<form id='double' method="GET" action="http://google.com/search">
<input name="q" type="text">
<button class="Submit"> Submmit here</button>
<button class="Submit popup"> Open new</button>
</form>