<body>
<form id="formId" onsubmit="addStudentData()"></form>
</body>
__
Scripts:
__
function addStudentData() {
let name = document.getElementById('sname').value;
let id = document.getElementById('sid').value;
let year = document.getElementById('syear').value;
let stream = document.getElementById('sstream').value;
/* Form validation -- the fields should not be empty. */
if (name == null || name == "", id == null || id == "", year == null || year == "", stream == null || stream == "") {
alert("Please fill all required fields.");
return false;
}
/* Making a JSON object using the form values */
let studentObj = { 'name': name, 'year': year, 'stream': stream };
/* Pushing record to sessionStorage after stringify JSON Object*/
sessionStorage.setItem(id, JSON.stringify(studentObj));
/* Redirecting back to home page*/
alert("Done. Press OK, redirect to home page.");
//HERE HERE HERE
window.location = "index.html";
}
do you have the code linked to your HTML in the first place?
if not use
<script src='script.js'></script>
in your HTML to make it a little bit easier
this:
let name = document.getElementById('sname').value;
let id = document.getElementById('sid').value;
let year = document.getElementById('syear').value;
let stream = document.getElementById('sstream').value;
suggest there is more code, please provide it in a way we can replicate the problem. There are many sites like jsfiddle where you can share your code
by default, a form will attempt to submit a request to the back-end of the website on the same url. If you don’t want this, you will have to use preventDefault()
on event
(which can be given as a parameter to the function that needs to execute when form is submitted)
MDN has good documentation about this:
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.