Zach Lucas
Zach Lucas

Reputation: 1641

How to prevent new window/tab opening after form post

I have a form submission like:

<form target="_blank" id="discussionForm" method="POST" enctype="multipart/form-data" action="<%=discussionURL%>">

Then I have a Submit button at the end. This works, and it posts to my db, but it opens a new tab with the url of the service that I'm using to post to the db. I don't want that new tab to open. I tried playing around with different targets, but I thought _blank would work. Any suggestions?

Upvotes: 4

Views: 20944

Answers (4)

I have added a solution to one of the thread here :

Recently I got this scenario and researched a lot to find the hack/solution.

Solution - If you can put a window names and refer same every time, then browser will make sure to open new tab if not opened already, otherwise it will just refresh the window.

Example snippet: Demo JSfiddle here

<form id="myForm" action="<URL>" method="POST" target="_blank" onsubmit="target_popup(this)">
    First name: <input type="text" name="fname"/><br/>
    Last name: <input type="text" name="lname"/><br/>
    <button type="submit" id="btnTest"> Submit</button>
</form>


<script>
var target_popup = function(form) {
    window.open('',//URL should be blank so that it will take form attributes.
                'UniqueWindowName', //window name
                'width=400,height=400,resizeable,scrollbars');
    form.target = 'UniqueWindowName';
}
</script>

Please refer my blog for more details

Upvotes: 0

petrosmm
petrosmm

Reputation: 550

In the case that someone does not have a target attribute, they may add the onclick and the onkeypress attributes with the following JS as shown below:

<form action="/Account/Login" class="form" method="post" onclick="return event.shiftKey !== true;" onkeypress="return !(event.keyCode === 13 && event.shiftKey);"> </form>

The onclick filters out any 'shift + click'. The onkeypress prevents 'shift + enter'.

Upvotes: 0

mechanicious
mechanicious

Reputation: 1616

You want to use this attribute when you want to display that what the submission of this form returned but on an other page/container _blank|_self|_parent|_top|framename, I suppose it was build back then when people were writing markup with the frames to give it a kind of html support, nowadays it's very bizare to use/need it.

"The target attribute specifies a name or a keyword that indicates where to display the response that is received after submitting the form." - W3Schools

Upvotes: 1

kapa
kapa

Reputation: 78731

Remove target attribute and it should be fine.

target="_blank" actually means it should open in a new tab/window.

Documentation (please always read the docs first)

Upvotes: 7

Related Questions