Jump to content

best way to do this?


acidglitter

Recommended Posts

i read that article linked to under the "best javascript practices" and have been trying to improve my codes. i just changed this today. is this the best way to be doing this?

 

 

the html:

<a href="thepage.php" onclick="return delete_check()">the link</a>

 

the javascript:

function delete_check() {
var answer = confirm("Are you sure you want to delete that?")
if (answer){
	return true;
} else {
	return false;
}
}

Link to comment
https://forums.phpfreaks.com/topic/96996-best-way-to-do-this/
Share on other sites

Looks OK to me, but it's a waste of extra lines. I'd just change the function to this

function delete_check() {
    return confirm("Are you sure you want to delete that?");
}

 

Or if you really want to clean it up don't use a function at all:

<a href="thepage.php" onclick="return confirm('Are you sure you want to delete that?');">the link</a>

 

Depending on your need this *may* be better. I'd incorporate the confirm into the link if it is only used on the page in one or two places. But, if multiple links need the same confirmationthen I would go with a function to make it easier to modify the process later on.

Link to comment
https://forums.phpfreaks.com/topic/96996-best-way-to-do-this/#findComment-496420
Share on other sites

What mjdamato said is all good. His return function was much more condense.

 

I personally don't use inline javascript calls though - javascript should all be kept externally. So in an external document, I would use:

 

function setListener()
{
    var target = document.getElementById("target")
    target.onclick = function()
   {
       return confirm("Are you sure you want to delete that?");     
   }
}

window.onload = function()
{
    setListener()
}

 

And then I would link to that document in the head of my script.

 

Finally, I would set the html to be this:

<a href="the_page.php" id="target">The Link</a>

 

 

Link to comment
https://forums.phpfreaks.com/topic/96996-best-way-to-do-this/#findComment-496518
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.