28

I have a form like this:

index.php

<form method="post" action="send.php">
  <textarea name="msg" id="msg"></textarea>
  <input type="submit" value="Send" />
</form>

So, if I enter something in textarea and clicked on "Send", it is submitted to "send.php" page. But I want to include another button for previewing it. That is, when this button is clicked, the above form is submitted to "preview.php" which will be opened in a new blank window/tab (original page ie. index.php will be there intact). This is to display a preview of the message, that the user is going to send.

I do not know how to do this.

0

5 Answers 5

34

Use Javascript to temporarily change the action and target:

<form method="post" action="send.php" id="idOfForm">
  <textarea name="msg" id="msg"></textarea>
  <input type="submit" value="Send" />
</form>
<button onclick="doPreview();">Preview</button>
<script type="text/javascript">
    function doPreview()
    {
        form=document.getElementById('idOfForm');
        form.target='_blank';
        form.action='preview.php';
        form.submit();
        form.action='send.php';
        form.target='';
    }
</script>
2
  • 1
    I didn't know you can have target blank for form! It's awesome!
    – Andrew Liu
    Jul 16, 2014 at 0:57
  • @VppMan It would be nice to see, how did you mix it.
    – Andremoniy
    Oct 19, 2015 at 10:56
14

There is now an attribute for the submit input that handles this:

<input type="submit" formaction=”differentThanNormalAction.php”>
0
6

Give your form an ID (form1). The action of the current form can be controlled like this:

function setPreview() {
    $('#form1').attr('target','_blank')
    $('#form1').attr('action','http://yourpreviewurl.php')
    $('#form1').submit()
}

function setSubmit() {
    $('#form1').attr('target','')
    $('#form1').attr('action','http://yourposturl.php')
    $('#form1').submit()
}

Have two buttons, both type="button", one to call setPreview and another to call setSubmit

1
  • This article goes one step further, and provides a fairly generic implementation.
    – jpaugh
    Oct 5, 2016 at 19:00
1

You can use JavaScript to change the action of the form when the button is clicked and then submit it.

Or simply submit the form via AJAX and then redirect after you get a response.

0
<form onreturn="someJavascriptFunction()" action="" method="">

creating a js function able to open this preview page

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.