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

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


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');    }  }});


if( !confirm('Are you sure you want to continue?')) {                    return false;   }


When you declare a variable anywhere in your function, it automatically gets "pulled" to the top as a local variable. When you call confirm as a function, it finds the local variable first (which hasn't been defined yet) and doesn't go up the scope chain to window where the function lives.

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

is the same as

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

You could 1) rename your variable, 2) call window.confirm("Dialog") telling it you want the global function instead of the local variable or 3) just put the confirm call inside an if

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