Cancel button not working with prompt method

This is really ridiculous, so I apologize in advance for any stupidity on my part… I cannot get the Cancel button to work with the following function. Every similar post I’ve found seems to indicate that this should work. It makes no difference whether I click OK or Cancel, or whether or not anything has been entered. The URL opens in a new window every time. When the user hits Cancel, it should just close the prompt dialog and die. What gives?

function myFunction(text,url)
var theId = prompt(“Enter ID:”, text);

Have you tried printing the value of theId ?

Yes. I inserted an alert, and it indicates that theId is indeed null when Cancel is clicked.

You shouldn’t be adding too much code that depends on values returned from debugging code.

Don’t forget to remove all alert, confirm and prompt calls from your code before it goes live.

I used to simply hit the “turn off JavaScript for this page” button when people left those debugging calls in their page but now I have them turned off completely since I no longer use them as the debugger and console.log make them completely unnecessary.

I only put the alert in there briefly for testing purposes, and actually the whole thing isn’t in production yet anyway. :slight_smile: So no thoughts on why it doesn’t work the way (I think) it should?

How are you calling the function? i.e. passing two strings to it?

Yes, and everything works exactly the way it should except that when you click Cancel, it pretty much does the exact same thing as if you had clicked OK. And, as I said, when I temporarily inserted an alert to check the value of theId when Cancel is clicked, it shows that the value is null, as it should be. It just doesn’t obey the “if” logic.

It apparently doesn’t care what I put in the “if” statement. I tried it with if(5==5)… same result. It executes both commands (the “if” AND the “else”). There has to be something very, very basic that I am not understanding here…

And I was right… stupid… I didn’t have an e.preventDefault(), so it was going to the URL as the default behavior, NOT because the “else” was kicking in. Sorry, everybody… :blush:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.