I am trying to display an alert message when the user is in the middle of editing and clicks accidentally on some other link.
I want to display this error message for certain link and not for others.
I thought of using 'window.onbeforeunload', parse the url to find the link that was clicked. However, when I try to use the string functions (split, substring, lastindexof, etc.) inside 'onbeforeunload', they do not work.
Rather than using onbeforeunload why don't you attach a click event on the links that takes the user elsewhere? That way you have the element that was clicked and you can then decide to user window.location or alert the user of missing fields.
Code:
<script type=text/javascript>
function handleLinkClick(event,el)
{
/* have your check logic here to either grab attributes off the link to determin if it is the
bad link or set up a confirm() box for the user to click if they are sure
they want to navigate away during editing.
*/
}
</script>
<a href='javascript:void(0)' onclick="handleLinkClick(event,this);" id=link1>Accidental Link</a>
The usecase is like this: User is editing something and the link he clicks accidentally can be a menu which is common to all views. If the onclick event is added to these links then the alert will show everytime the user clicks these links, even though he is not editing anything.
The usecase is like this: User is editing something and the link he clicks accidentally can be a menu which is common to all views. If the onclick event is added to these links then the alert will show everytime the user clicks these links, even though he is not editing anything.
I have to avoid this behaviour.
Ok, to clarify what I suggested earlier:
One way to do it is:
1) add an onclick event handler function to the relevent links.
...
...
Your options include adding an onclick manually to each relevent link, which most likely would not be practical, or you could give each relevent link a class name and then have an onload function that attaches an onclick event handler to display window.confirm() to links with that class name.
Bookmarks