javascript form submit problem stopping link flow
I have a form, I want to track if its dirty, if it is, if the user clicks links to go away from page, I want to prompt them to save, ideally I want to pass the url to the server, if the server save works, it redirects the url, if not, it comes back to the same page with validation errors.
Here is my code:
var isDirty;
isDirty = 0;
function setDirty() {
isDirty = 1;
}
function checkSave()
{
var sSave;
if (isDirty == 1)
{
sSave = window.confirm("You开发者_如何学编程 have some changes that have not been saved. Click OK to save now or CANCEL to continue without saving.");
if (sSave == true)
{
$('submitted_by_javascript').value = "true";
$('main-edit-form').submit();
return false;
}
else
{
return true;
}
}
}
<a href="/registrar_data_forms/41/contacts/71/edit" onclick="checkSave();">Edit</a>
My problem is first it seems even when I return false from my checkSave() function, the page still gets redirected to the link clicked.
The odd thing is sometimes the form gets submitted, works, then the link is followed. Sometimes the link is just followed and the form is never really submitted...
In your <a> tag, change the onclick handler to this:
onclick="return checkSave();"
The href will be followed unless onclick explicitly returns false, so you need to pass the return value from checkSave().
I believe you need to explicity return something from the onclick:
onclick="return checkSave();"
to prevent the navigation
精彩评论