HTML form with two submit buttons and two “target” attributes

前端 未结 15 2261
暗喜
暗喜 2020-11-29 20:02

I have one HTML

.

The form has only one action=\"\" attribute.

However I wish to have two different target=\"\" attribu

相关标签:
15条回答
  • 2020-11-29 20:27

    Have both buttons submit to the current page and then add this code at the top:

    <?php
        if(isset($_GET['firstButtonName'])
            header("Location: first-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
        if(isset($_GET['secondButtonName'])
            header("Location: second-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
    ?>
    

    It could also be done using $_SESSION if you don't want them to see the variables.

    0 讨论(0)
  • 2020-11-29 20:29

    It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.

    Anyhow, with that in mind, this should do it:

    <form id='myform' action='jquery.php' method='GET'>
        <input type='submit' id='btn1' value='Normal Submit'>
        <input type='button' id='btn2' value='New Window'>
    </form>
    

    With this javascript:

    var form = document.getElementById('myform');
    form.onsubmit = function() {
        form.target = '_self';
    };
    
    document.getElementById('btn2').onclick = function() {
        form.target = '_blank';
        form.submit();
    }
    

    Approaches that bind code to the submit button's click event will not work on IE.

    0 讨论(0)
  • 2020-11-29 20:31

    Example:

    <input 
      type="submit" 
      onclick="this.form.action='new_target.php?do=alternative_submit'" 
      value="Alternative Save"
    />
    

    Voila. Very "fancy", three word JavaScript!

    0 讨论(0)
提交回复
热议问题