Jader Dias
Jader Dias

Reputation: 90475

How to make a link that POSTs and opens in a new window if the users chooses to do so?

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

Answers (2)

mplungjan
mplungjan

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

T.J. Crowder
T.J. Crowder

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

Related Questions