Reputation: 90475
Usually links open in the same window or in a new tab depending on whether the users clicked or Ctrl+clicked. But when I have to POST, instead of GET, I have to create a form and put
href="javascript:document.forms['myForm'].submit()"
instead of the url. Is there any way in javascript to detect whether the user clicked or Ctrl+clicked so I can set the proper target for my form?
Upvotes: 1
Views: 80
Reputation: 178061
I strongly suggest never to use the javascript protocol.
The onclick event can handle what you want and you can cancel the href
I like to use links for semantic and accessibility reasons instead of using a scripted span or similar
<a href="#" id="myFormSubmit">Submit</a>
or better:
<a href="javascriptrequired.html" id="myFormSubmit">Submit</a>
using
window.onload=function() {
document.getElementById("myFormSubmit").onclick=function(e) {
var event = e?e:event, form = document.forms['myForm'];
form.target = (event.ctrlKey || event.metaKey) ? '_blank' : '';// TJ/Jader Dias
form.submit(); // or form.submitButton.click(); if any submit handler exists
if (event.preventDefault) event.preventDefault();
else return false; // cancel the click
}
}
Upvotes: 1
Reputation: 1074495
If you put a click handler on the link, you can look for the ctrlKey
property on the event object. Here's the attribute version because you're doing something similar with the href
(normally I tend to avoid using attributes for event handlers):
onclick="document.forms['myForm'].target = (event.ctrlKey || event.metaKey) ? '_blank' : ''"
E.g.:
<a href="javascript:document.forms['myForm'].submit()"
onclick="document.forms['myForm'].target = (event.ctrlKey || event.metaKey) ? '_blank' : ''"
>...</a>
Or you can do the whole thing in the onclick
:
<a href="#submitform"
onclick="var form = document.forms['myForm']; form.target = (event.ctrlKey || event.metaKey) ? '_blank' : ''; form.submit(); return false;"
>...</a>
Upvotes: 1