I am creating a form and the onsubmit
attribute has a form validation boolean method. At the end of the method, it does not matter whether or not none of the invalid inputs have returned false
, the sessionStorage
variable is to be updated to true
so that upon loading the page again the variable will be rechecked. Why is the variable still false
whether none of the inputs returned false
or not? Keep in mind that the form action
attribute leads to the same page (form page). This is how my validation looks like:
<form action="form.jsp" onsubmit="return validate()">
<input type="text" id="foo" />
<input type="submit">
</form>
var input=document.getElementById("foo"); // textbox
function validate()
{
if (input.value.trim() === "") {
return false;
}
sessionStorage.setItem("submitted","true");
}
Keep in mind that all form inputs exist and the sessionStorage variable is not updated even after the function doesn't return false
.
CodePudding user response:
Try wrapping the sessionStorage call in a try/catch to see why it's failing.
function validate() {
var input = document.getElementById("foo"); // textbox
console.log('validate', input);
if (input.value.trim() === "") {
return false;
}
try {
sessionStorage.setItem("submitted", "true");
} catch (e) {
console.log(e);
return false;
}
// (for demostration purposes return false)
return false;
}
<form onsubmit="return validate()">
<input type="text" id="foo" />
<input type=submit>
</form>
Alternatively you can use the "Preserve log" checkbox in DevTools to retain the console errors.
CodePudding user response:
Looking at your jsfiddle
code, the reason is because you are checking its value like this:
if (sessionStorage.getItem("submitted") == true)
This is not accurate as the data stored there is a string... so to fix this you can do:
if (sessionStorage.getItem("submitted") == 'true')
You actually can't even check it like this:
if (sessionStorage.getItem("submitted"))
Because that will return true
for any non-null value, even 'false'
.