How to prevent new window/tab opening after form post
Solution 1
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)
Solution 2
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'.
Solution 3
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
Zach Lucas
Mobile Engineer @ MakeSpace Favorite iOS-specific libraries: ReactiveCocoa (w/ MVVM) Quick & Nimble for unit testing Danger Currently playing around with: React Native on both iOS & Android (and VR!) Firebase
Updated on June 04, 2022Comments
-
Zach Lucas almost 2 years
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?
-
Zach Lucas over 10 yearsif I don't use target="_blank", it replaces the current tab with a blank screen (my ReST service's response). I don't want it opening anything. thoughts?
-
kapa over 10 years@ZachLucas You haven't said what was the intended behaviour. In this case, you could catch the
submit
event for the form, prevent submitting, and post the data using AJAX in the background. Or redirect the form to a hiddeniframe
- this can be done with thetarget
attribute, check the docs I linked :).form
s work like this by default, they open the page in theaction
, so you have to either prevent it (JS) or find a way around (iframe).