setting target _blank for just one form submit action

前端 未结 3 1345
刺人心
刺人心 2021-01-11 18:22

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

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-11 19:19

    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/

提交回复
热议问题