0

I have a FORM with two submit button. What I wanted to happen is when the first button is clicked, it will submit on the tab itself. If the second button is clicked, it will proceed to a new tab.

HTML :

<form id="frm" action="" method="post" target="_blank">
<input type="text" value="data" name="data">
    <input type="submit" name="first" id="first" value="Self"/>
    <input type="submit" name="second" id="second" value="Tab"/>
</form>

Javascript :

$('form#frm').submit(function(){
    var open_new_tab = false;

    if($('#second').click){
        open_new_tab = true;
    }

    if ( open_new_tab ) {
        alert('opening to new tab');
        $('form#frm').attr('target', '_blank');
    }
    else{
        alert('opening to self_page');
        $('form#frm').attr('target', '_self');
    }
});

Please check this fiddle: Two Submit button in One Form

Note: I wanted to pass on some data inside the FORM into the new tab or in the tab itself.

1 Answers1

2

You're nearly there, first you need to make open_new_tab available in the global scope by defining it outside your event handlers, then redefine the variable on the click event of either button. Then you can check for the value during your submit handler:

var open_new_tab = false; // variable now available in global scope

$('#second').click(function(){
    open_new_tab = true;
});

$('#first').click(function() {
    open_new_tab = false;
});

$('form#frm').submit(function(){    
    if (open_new_tab) {
        alert('opening to new tab');
        $(this).attr('target', '_blank');
    } else{
        alert('opening to self_page');
        $(this).attr('target', '_self');
    }
});

Fiddle

scrowler
  • 24,273
  • 9
  • 60
  • 92