I have three file index.html,success.html and index.js and I want to validate form than redirect accordingly and prind form data on success page? anable to access variable from one function to other As code my code here from
function check() {
x = document.forms.myform.fname.value;
if (x == "") {
alert("First Name should be filled out!");
return false;
} else {
alert("Login Successful");
window.location.href = "success.html";
return false;
}
}
// onload name function from success.html
function name() {
document.getElementById('fn').innerHTML = x;
}
<body>
<h1>Welcome to Form Validation</h1>
<form method="post" action="success.html" name="myform" onsubmit="return(check())">
<label>First Name</label>
<input type="text" placeholder="First Name" name="fname">
<button type="submit">Submit</button>
</form>
<script src="./index.js"></script>
</body>
success.html
function check() {
x = document.forms.myform.fname.value;
if (x == "") {
alert("First Name should be filled out!");
return false;
} else {
alert("Login Successful");
window.location.href = "success.html";
return false;
}
}
// onload name function from success.html
function name() {
document.getElementById('fn').innerHTML = x;
}
<head>
<script src="./index.js"></script>
</head>
<body onload="name()">
<h1>Your form is submitted successfull.</h1>
<p>Thanks</p>
<div id="fn">Name Here</div>
<hr width="50%">
</body>
The easiest way to do that without having a server side component is to utilize GET instead of POST in your form. Also, take away the window.location line - you want the form to submit naturally
function check() {
if (document.forms.myform.fname.value == "") {
alert("First Name should be filled out!");
return false;
}
return true;
}
<form method="get" action="success.html" name="myform" onsubmit="return(check())">
<label>First Name</label>
<input type="text" placeholder="First Name" name="fname">
<button type="submit">Submit</button>
</form>
And on the receiving page access the page URL with window.location.href...
var url_string = "http://www.example.com/success.html?fname=John"; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("fname");
console.log(c);