Javascript - confirm() inside a jquery .click() function

Mechaflash picture Mechaflash · Nov 10, 2011 · Viewed 69.5k times · Source

I have the following

$("element").click(function() {
  var foo=bar;
  if ( foo == "bar" ) {
   confirm('Dialogue');
  }
});

But I would like to bool the confirm function. I've already tried

$("element").click(function() {
  var foo=bar;
  if ( foo == "bar" ) {
    var confirm=confirm('Dialogue');
    if (confirm==true) {
      alert('true');
    } else {
      alert('false');
    }
  }
});

But no confirmation box is generated. How can I accomplish this?

Answer

epascarello picture epascarello · Nov 10, 2011

You have a few issues. First issue is you are defining a variable with the name confirm. Not good! Rename it to isGood or something else.

The other bug is right here:

if (confirm=true) {

confirm=true is assignment, not a comparison.

It needs to be

if (confirm==true) {

or just

if (confirm) {

So your code would be something like

var bar = "bar";
$("button").click(function() {
  var foo=bar;
  if ( foo == "bar" ) {
    var isGood=confirm('Dialogue');
    if (isGood) {
      alert('true');
    } else {
      alert('false');
    }
  }
});