Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setting target _blank for just one form submit action

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 the form target=_blank so that the form submission results open in a new window.

Is there an easy way to do this?

Doing this works for both actions:

<%= simple_form_for @thingy, :target => '_blank' do |f| %>

I've mucked around with using jQuery to set the target on the form onclick, but with no luck.

like image 795
ipd Avatar asked Nov 21 '12 00:11

ipd


1 Answers

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/

like image 199
David Hellsing Avatar answered Sep 29 '22 00:09

David Hellsing