safari javascript issue
attached javascript does not work in safari.
this script displays a confirmation message before navigating away from the current page.
surprisingly this works for the first time in safari (but not during subsequent submit).
Scenario:
- user makes some changes and press submit button
- confirmation message displayed to user
- user decided to press cancel button to stay back on the same page
- but afterword user unable to invoke submit again.
- submit button does not work.
P.S: This code works perfectly with othere browser i.e. IE7/8, FireFox.
function checksave() {
if (formIsDirty(myForm)) {
return "The form has been changed...";
}
}
function formIsDirty(form) {
for (var i = 0; i < form.elements.length; i++) {
var element = form.elements[i];
var type = element.type;
if (type == "checkbox" || type == "radio") {
if (element.checked != element.defaultChecked) {
return true;
}
}
else if (type == "hidden" || type == "password" || type == "text" ||
type == "textarea") {
if (element.value != element.defaultValue) {
return true;
}
}
else if (type == "select-one" || type == "select-multiple") {
开发者_高级运维 for (var j = 0; j < element.options.length; j++) {
if (element.options[j].selected !=
element.options[j].defaultSelected) {
return true;
}
}
}
}
return false;
}
<body OnBeforeUnload ="return checksave();">
<form id="myForm" >
<table border="1">
<tr> <td>Enter Text:</td><td><input id="text1" type="text" value=""/> <br/> </td></tr>
<tr> <td><input id="button1" type="submit" value="Submit1"/> <br/> </td> <td><input id="button2" type="submit" value="Submit2"/> <br/> </td></tr>
</table>
</form>
</body>
Yeah, it's a bug in WebKit, though one that seems to be fixed in current Chrome versions for me.
Seems when a form submission is cancelled from a beforeunload prompt, all forms on the page become unsubmittable (the submit
event still fires but the submission does not navigate) until any form field on the page is changed. (This is nothing to do with your own form-changedness checking. The browser itself blocks the navigation until it notices a change. Maybe some kind of form-multiple-submission-prevention trick gone wrong, or something?)
Normally you wouldn't notice since typically you'd put a different handler on form.onsubmit
which would short-circuit the onbeforeunload
(since generally if the user is clicking to submit the form, they know they've changed something on it, and want to save the change).
(Incidentally, avoid use of myForm
as a global variable to reference the element with id="myForm
. This is an IE hack that some other browsers have now implemented but only in Quirks Mode, and you don't want to be in Quirks Mode. Add a <!DOCTYPE>
declaration and use document.getElementById('myForm')
.)
精彩评论