Forum Moderators: open

Message Too Old, No Replies

How can I rewrite this function?

         

dbarasuk

12:43 pm on May 25, 2008 (gmt 0)

10+ Year Member



Hi,
I wrote a function to direct me to a page in case the OK button is clicked or stay on the same page if the Cancel button is clicked instead.

The function is as follows:

function confirmer()
{
var answer = confirm("You need to be logged in to visualize this CV.\nWould you like to continue?");
if(answer)
{
window.location = "../html/Curriculum Vitae.php"; // This is where I want to navigate to
}
if(!answer)
{
window.location = "../html/acceuil.php"; // This is where I am currently(current page) and want to stay if Cancel is clicked
}

}
The anchor being clicked to trigger that function is echoed by PHP and included in the page where the anchor being clicked resides as follows:

echo'<li ><a href="../html/Curriculum Vitae.php" onClick="return confirmer()">Curriculum Vitae</A></li>';

So my problem is: No matter which button of the popup box I click, I am immediately directed to the page indicated in the HTML echoed by PHP here above.

SO, What can I do so that, in case the Cancel button clicked I stay on the same page?

Thanks

poppyrich

2:32 pm on May 25, 2008 (gmt 0)

10+ Year Member



Change the conditionals to this and it will work:

if(answer==true)

if(answer==false)

rocknbil

3:58 pm on May 25, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It will still move to the page. You have return in your link, but the function doesn't return anything.

if(answer==true) { do_your_redirect; }
return false;

There's no reason to do window.location on the second condition if you want to stay on the current page. This will just refresh the page, unnecessary. you already have return in your link,

<a href="../html/Curriculum Vitae.php" onClick="return confirmer()">

So if you just eliminate the second condition in your function and return false, it will stop the link from performing it's normal action.

Complete rewrite:
function confirmer() {
var answer = confirm("You need to be logged in to visualize this CV.\nWould you like to continue?");
if(answer==true){
window.location = "../html/Curriculum Vitae.php";
}
return false;
}

echo'<li><a href="../html/Curriculum Vitae.php" onClick="return confirmer()">Curriculum Vitae</a></li>';

I would also suggest, although they will "work," you should try to avoid spaces in file names. This

Curriculum Vitae.php

turns into this in the address bar:

Curriculum%20Vitae.php

[edited by: rocknbil at 4:00 pm (utc) on May 25, 2008]

penders

4:00 pm on May 25, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Just a point, this...
if(answer==true) 
if(answer==false)

is the same as this...

if(answer) 
if(!answer)

no difference in execution, just in readability. Personally, I'd go for the 2nd.

------

Also, if you need to do something like:

if (something) {...} 
if (!something) {...}

It is best to code this as:

if (something) {...} 
else {...}

------

However, your anchor/link at the moment will ALWAYS follow the value stored in the HREF attribute because you are not returning anything from your function. Your confirmer() function needs to

return false;
in order to prevent the actual link from being followed by the browser.

Also, if you don't want to do anything (ie. stay on the same page) if the user hits [Cancel] then you don't need to do anything! You don't need to redirect to the same page; this will cause the browser to effectively refresh the page. (I suspect you added this code later in order to try to get it to work?)

So, your function could be rewritten as:

function confirmer(anchor) { 
var answer = confirm("You need to be logged in to visualize this CV.\nWould you like to continue?");
if (answer) {
window.location = anchor.href;
}
return false;
}

And your link slightly modified to read:

<a href="../html/CurriculumVitae.php" onClick="return confirmer(this)">Curriculum Vitae</A>

Note I have removed the 'space' from your "Curriculum Vitae.php" filename. (You would need to do the same to the actual file.) This is just good practise (and it is your CV afterall!). The browser is probably automatically escaping this for you... the '%20' in the resulting URL. (See this thread: My links have a "%" symbol all over them [webmasterworld.com])

Also, I am passing

this
(a reference to the current object) to the function and in the function using
this.href
to refer to the HREF of the anchor. This avoids having the type the URL twice. Making the script less prone to errors and making the code more portable. You could pass the confirmation messsage to the function as well and you have a generic function that can be used anywhere.

---<edit>---
(Ha, looks like rocknbil got there first! ;)

rocknbil

4:40 pm on May 25, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



P'raps. But portable functions are soooo much better. :-)

dbarasuk

5:35 pm on May 25, 2008 (gmt 0)

10+ Year Member



Thanks,
it works now.

poppyrich

6:13 am on May 26, 2008 (gmt 0)

10+ Year Member



@ penders

I must have been half asleep - you are quite right that, in the context of the code originally posted:


This...
if(answer==true)
if(answer==false)

is the same as this...
if(answer)
if(!answer)

in that both get you the same result in the context of the confirmer function that began this thread.
(But they are not equivalent, many things evaluate to false - an empty string, a variable with no assigned value, the number 0, but they are not the boolean "false" and in some contexts that makes quite a bit of difference.)

If I was going to rewrite the function for terseness, since the confirm returns either (boolean) true or false, I would skip the variable declaration entirely and put the confirm within the if statement:

function confirmer()
{
if(confirm("You need to be logged in to visualize this CV.\nWould you like to continue?")){
alert('You clicked OK');
}else{
alert('You clicked Cancel');
}

(However, the altered link suggested with the onclick event is a lot more elegant and terser still.)

penders

9:54 am on May 26, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



(But they are not equivalent, many things evaluate to false - an empty string, a variable with no assigned value, the number 0, but they are not the boolean "false" and in some contexts that makes quite a bit of difference.)

@poppyrich - Yes, whether a variable is actually the (boolean)true or whether it simply evaluates to true can certainly be important, however, I think you are mixing up the equality (==) and identity (===) operators in this case. Identity being triple equals. Or inequality (!=) and nonidentity (!==).

These are always equivalent as far as I'm aware:

if (answer == true) {//DOTHIS} 
if (answer) {//DOTHAT}

If answer evaluates to true (ie. 1, "1" or indeed the (boolean)true etc.) then DOTHIS and DOTHAT will execute.

However, these are not always equivalent:

if (answer === true) {//DOTHIS} 
if (answer) {//DOTHAT}

If answer is "1" then only DOTHAT will execute, since it evaluates to true, but is not the (boolean)true. DOTHIS will not execute since answer is not the same type; it is not identical.

In the case of the JS confirm() function which, as you suggest, returns (boolean)true or false, then the comparison could also be written:

if (answer === true)

But this is unnecessary.

(Dang, now I've got Meatloaf rocking in my head...!? "But I won't DOTHAT..." ;)

poppyrich

2:00 pm on May 28, 2008 (gmt 0)

10+ Year Member



@penders

To split hairs just a little further, after thinking about it, there are only two situations I could come up with where the syntax used to check for true or false makes a real difference.

1) Looping - since the script parser has to do type coercion to compare "falsy" or "truthy" values (in other words, NOT boolean), the == should not be used because there might actually be a performance hit.
Douglas Crockford - the Emily Post* of javascript - and creator of JSLint says this:

=== and !== Operators:
It is almost always better to use the === and !== operators. The == and != operators do type coercion. In particular, do not use == to compare against falsy values.

Crockford's advice is a bit much for me, I don't think I've ever used the test for strict equivalence (===).

2) A situation where using == might make it clearer to other programmers the nature of what, exactly, is being checked as true and false.

*I'm dating myself - but even so I haven't heard that name mentioned in years. Emily Post wrote books on manners and etiquette and was the self appointed arbiter of such - at least in America - in the early to mid twentieth century.

penders

11:16 pm on May 29, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



1) equality(==) / identity(===)... a performance hit

Hhhmmm, possibly, although if you know the types are going to be the same then using equality (==) should cause no type conversion; no performance hit(?) And if the types could be different and you are using identity(===) for performance then your script might be wrong, since equality(==) would/could give different results? I guess it depends on the script?

A reason for having to differentiate between (boolean)false and something that evaluates to false... if you have a function that returns (boolean)false on error but could return a valid value that evaluated to false (the number 0 for instance in determining the position of a character within a string). Far more common in PHP TBH (many standard funcs do this sort of thing), but could equally apply to JS.