10

How do I make one of those hyperlinks where when you click it, it will display a popup asking "are you sure?"

<INPUT TYPE="Button" NAME="confirm" VALUE="???" onClick="message()">

I already have a message() function working. I just need to know what the input type for a hyperlink would be.

Tomalak
  • 332,285
  • 67
  • 532
  • 628

4 Answers4

23
<a href="http://somewhere_else" onclick="return confirm()">

When the user clicks the link, the confirm function will be called. If the confirm function returns false, the link traversal is cancelled, if true is returned, the link is traversed.

JacquesB
  • 41,662
  • 13
  • 71
  • 86
15
<a href="http://something.com" onclick="return confirmAction()">try to click, I dare you</a>

with the function

function confirmAction(){
      var confirmed = confirm("Are you sure? This will remove this entry forever.");
      return confirmed;
}

(you can also return the confirm right away, I separated it for the sake of readability)

Tested in FF, Chrome and IE

marcgg
  • 65,020
  • 52
  • 178
  • 231
2

As Nahom said, except I would put the javascript:message() call directly in the href part (no need for onclik then).

Note: leaving the JavaScript call in the onClick has a benefit: in the href attribute, you can put a URL to go to if the user doesn't have JavaScript enabled. That way, if they do have JS, your code gets run. If they don't, they go somewhere where they are instructed to enable it (perhaps).

Now, your message routine must not only ask the question, but also use the answer: if positive, it must call submit() on the form to post the form. You can pass this in the call to ease the fetching of the form.

Personally, I would go for a button (input tag as you show) instead of a simple link to do the process: it would use a more familiar paradigm for the users.

[EDIT] Since I prefer to verify answers I give, I wrote a simple test:

<script type="text/javascript" language="JavaScript">
function AskAndSubmit(t)
{
  var answer = confirm("Are you sure you want to do this?");
  if (answer)
  {
    t.form.submit();
  }
}
</script>

<form action="Tests/Test.html" method="GET" name="subscriberAddForm">
<input type="hidden" name="locationId" value="2721"/>
<input type="text" name="text" value="3.1415926535897732384"/>
<input type="button" name="Confirm" value="Submit this form" onclick="AskAndSubmit(this)"/>
</form>

Yes, the submit just reload the page here... Tested only in FF3.

[EDIT] Followed suggestion in the comments... :-)

sugardaddy
  • 433
  • 1
  • 4
  • 10
PhiLho
  • 40,535
  • 6
  • 96
  • 134
  • "t.parentNode" works for this example, but it is brittle because it contains an assumption. Better is "t.form". – Tomalak Nov 16 '08 at 12:02
0
<a href="#" onclick="message(); return false;">???</a>

This answer would be OK only when the click need NOT navigate the user to another page.

Nahom Tijnam
  • 4,726
  • 5
  • 25
  • 25