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?
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');
}
}
});
All of the comments about the comparison are correct, however, the reason the confirm dialog is not showing is that you are wiping out the confirm box object.
Change the name of the confirm
var.
$(element).click(function() {
var confirm1 = confirm('Dialogue');
if (confirm1) {
alert('true');
} else {
alert('false');
}
});
http://jsfiddle.net/xjGZj/
Compare that to this one which doesn't work.
$(element).click(function() {
var confirm = confirm('Dialogue');
if (confirm) {
alert('true');
} else {
alert('false');
}
});
http://jsfiddle.net/xjGZj/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With