I'm having issues with form submit - somehow when user has not clicked submit button, upon refresh of the page, the validation is ran and the error message is shown on the page.
Anyone knows why onsubmit doesnt work here, and how do i only show the error on form submit?
HTML:
<form action="#" method="POST" name="signupForm" class="ggForm" onsubmit="return validateSignupForm()">
<div class="email">
<label for="emailBox">Email*:</label>
<input type="email" name="custEmail" id="emailBox" placeholder="john.doe#gmail.com" required
pattern="^[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,4}$" title="(The email entered is invalid)">
</div>
<!-- submit button below -->
<div>
<input type="submit" value="Submit Form">
</div>
<p id="potentialErrors"></p>
</form>
JS:
window.onload = init;
function init() {
document.forms["signupForm"].onsubmit = validateSignupForm();
}
function validateSignupForm() {
console.log("ran");
var errMsg = "";
var email = document.forms["signupForm"]["custEmail"].value;
if (email == "") {
errMsg += "<br>Email must be filled out";
}
// when there's errors in any field, put as message below submit button
if (errMsg != "") {
document.getElementById("potentialErrors").innerHTML = errMsg;
//change the error message css
$("p#potentialErrors").css("height","50");
$("p#potentialErrors").attr("width","500");
$("p#potentialErrors").css("font-weight","bold");
$("p#potentialErrors").css("color","red");
return false;
}
return true;
}
Edit FYI: i have edited the above code into this codepen, it is working now:
https://codepen.io/vadevalor/pen/VwepxdY
need to add jquery library,
need to remove html validation
as per comments for this question, need to remove () in the js function
You need to add onsubmit in the form event.preventDefault();, next add jquery library to you code.
So:
<script
src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"></script>
<form action="#" method="POST" name="signupForm" class="ggForm" onsubmit="event.preventDefault(); return validateSignupForm()">
Related
I have added Google reCaptcha v3 script to my form. The form also includes validation that alerts the user to complete the input field. Now when the user clicks on submit button directly, an alert is shown and when OK is clicked the page refreshes and form data is submitted in the backend. I have tried adding return false and e.preventdefault() in the function but the page still resets after the alert. If I try to add any additional condition to the data-callback function, the submit button stops working.
HTML
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js"></script>
<script>
function onSubmit(token) {
document.getElementById("demo-form").submit();
}
</script>
<script>
function validateForm() {
var fname = document.forms.WebForm.fname.value;
if (fname == "") {
alert("Please fill out all the fields");
return false;
}
}
</script>
</head>
<body>
</style>
<div class="container">
<form action="https://www.samepage.com" method="post" id="demo-form" name="WebForm">
<div>
<div>
<input name="fname" id="fname" type="text" placeholder="First name*" required/>
</div>
</div>
<div>
<div>
<input type = "submit" style = "font-weight: bold;" value="Submit" class="g-recaptcha button" data-sitekey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
data-callback='onSubmit'
data-action='submit'
onClick="return validateForm()"/>
</div>
</div>
</form>
</div>
</body>
</html>
Even the required attribute in the input tag doesn't work with the recaptcha script added. When I remove the data-callback attribute and the supporting script functions, the alert and form works as expected.
Apologies if this question isn't layed out correctly (my first time using stack overflow).
I'm trying to validate if my inputs on a form are filled in when a user presses submit, it alerts the user when the inputs are empty but also when they are not, I'm not sure whats going wrong. Here is my Javascript:
<script>
function validation() {
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
Here is a link to an expanded part of the code for reference:https://pastebin.com/Dj5fA3gB
The general syntax for accessing a form element and element's value are:
document.forms[number].elements[number]
document.forms[number].elements[number].value
If you are using submitButton as in and you are calling validation on onSubmit of the form then you need to call event.preventDefault();
<!DOCTYPE html>
<html>
<body>
<form onsubmit="validation()" name="bookingForm">
First Name: <input type="text" name="id" value="Donald"><br>
Last Name: <input type="text" name="lname" value="Duck">
<input type="submit" value="Submit" />
</form>
<script>
function validation() {
event.preventDefault();
var x = document.forms["bookingForm"]["id"].value;
if (x == "") {
alert("Ensure all fileds are filled");
return false;
} else {
sendSMS();
alert("Success");
return true;
}
}
</script>
</body>
</html>
As suggested in my comment the most clean solution is to use the html attribute required by adding it to your inputs.
Looks something like this.
<form>
<input type="text" name="example" required>
<input type="submit" name="send">
</form>
The biggest advantage is that it works without any additional JS which is in my opinion always the prefered solution.
You didn't include return keyword in the form tag and adding unnecessary keyword "name" in the form tag.
<form onsubmit="return validation()" method="POST"
action="">
remove the "name" attribute from form tag and add action attribute.
Within the parenthesis in the action attribute, mention what happen if your validation success
Ex:(this code help you understand "action" attribute)
<form onsubmit="return productsvalidationform();" method="POST"
action="AddProductServlet">
when the form was successfully validated, I directed to AddProductServlet.(AddProductServlet is JSP servlet).
so that mention where do you need to redirect.
Peeps,
I see this question has been asked but they either don't have validation function right or there are some syntax errors.
Here is my code; it is supposed to check fields are not blank then if they are not blank it passes them to the next page.
What happens with my codes is that it does check the validation but right after the Alert pop-up it goes to the next page. My intention is to not go to the next page unless all fields are filled.
Any hints would be greatly appreciated.
<html>
<head>
<script type="text/javascript">
function RegValidation() {
var txtURL,
if (!txtURL) {
alert("URL is mandatory!");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="RegisterForm" action="RegConfirm.php" method="post">
<p><input type="text" name="txtURL"></p>
<p><input type="submit" value="Register" onclick="Register()"></p>
</form>
</body>
<script type="text/javascript">
function Register() {
if (!RegValidation()) return;
}
</script>
Instead of onclick function on submit button try onsubmit in form tag..
the working code of the jsfiddle is here
<form name="RegisterForm" action="RegConfirm.php" method="post" onSubmit="return Register()">
<p><input type="text" name="txtURL" id="txtURL"></p>
<p><input type="submit" value="Register"></p>
</form>
function Register() {
return RegValidation();
}
function RegValidation() {
var txtURL = document.getElementById('txtURL').value;
if (!txtURL) {
alert("URL is mandatory!");
// txtURLFocus();
return false;
}
return true;
}
you need to assign the value of the field to the var you are testing
You need a focus function that is not defined in the code you gave.
You now only execute a function on click instead of returning it. It is not recommended to assign handlers to a submit button so I have assigned it to the submit event where it belongs
Here is an unobtrusive working version
window.onload = function() {
document.getElementById("RegisterForm").onsubmit = function() {
var txtURL = this.txtURL.valuel
if (!txtURL) {
alert("URL is mandatory!");
this.txtURL.focus();
return false;
}
return true;
}
}
<form name="RegisterForm" id="RegisterForm" action="RegConfirm.php" method="post">
<p><input type="text" name="txtURL"></p>
<p><input type="submit" value="Register"></p>
</form>
<form id="loginForm">
<p id="usernameLabel">Username:</p>
<input type="text" name="username" id="username" placeholder="username"/><br>
<p id="passwordLabel">Password: </p>
<input type="password" name="password" id="password" placeholder="password"/><br>
<input id="loginButton" type="submit" value="Login!" onsubmit="validateForm()">
</form>
<p id="loginMessage">Please Login!</p>
<script type="text/javascript">
function validateForm() {
var un = document.loginForm.username.value;
var pw = document.loginForm.password.value;
var username = "MitchWardle";
var password = "123abc456";
if ((un == username) && (pw == password)) {
window.location = "content.html";
return false;
}
else {
alert ("Login was unsuccessful, please check your username and password");
}
}
</script>
I have created a little login form on Javascript and I want it to navigate to Content.html when username and password are correct but when I click my Login button it just removes the text from the text box's, can anybody see whats wrong?
you need to return false to prevent default action of submitting the form , page gets refresh andyou loss your data, you can set type of submit button to
type="button"
or can change onsubmit to
onclick="validateForm(); return false; "
Just a couple things are off, but it's almost there:
The onsubmit handler is used at the form level. Either move the onsubmit to the <form> element or change it to an onclick event for the <input> element.
In order to reference the text fields the way you are, the <form> element also needs a name attribute. i.e. name="loginForm"
Do this:
Remove onsubmit from button add it to form.
Change id of form to name.
In the onsubmit of form append return false;.
Remove return false; from the if statements.
Change document.loginForm line to this:
document.forms['loginForm'].elements['username'].value //username/password depends.
Hope it works.
I have had the same problem as you before, and I solved it by changing the submit button to <input type="button" onclick="login();" />, and everything worked. However, the user then cannot submit the form with enter key (because there's no submit button in the form).
That is the thing.
My head:
<script language="JavaScript">
function checkIt(){
var pass = document.form1.value;
if (pass == "1234")
{
alert("Please input a Value");
return false;
}
else
{
alert('Code has accepted : you can try another');
return true;
}
}
window.onload = checkIt();
</script>
My body:
<form action="#" method="post" id="form1" onsubmit="checkIt();">
<input type="password" id="sn" name="sn" placeholder="Enter Your Password">
<img src="ok.gif" onclick="submit();" style="cursor: pointer;">
</form>
Can anybody tell me what I am doing wrong? It is not working. I need it to be able to compare entered value named sn, with var pass.
I am noob and not a native speaker, so stay calm, please:)
Fix your script
// to get the input value
var pass = document.getElementById("sn").value;
And on your form you have to return the result of the function
onsubmit="return checkIt();"
Also remove window.onload = checkIt(); that will validate the form before you enter any value
try the following:
Javascript
<script language="JavaScript">
function checkIt(){
var pass = document.getElementById("sn").value;
if (pass == "1234")
{
alert("Please input a Value");
return false;
}
else
{
alert('Code has accepted : you can try another');
return true;
}
}
</script>
HTML
<form action="#" method="post" id="form1" onsubmit="return checkIt();">
<input type="password" id="sn" name="sn" placeholder="Enter Your Password">
<img src="ok.gif" onclick="document.getElementById("form1").submit();" style="cursor: pointer;">
</form>
Try var pass = document.getElementById('sn').value;
onclick="form1.submit()" and onsubmit="return checkIt()"
You are calling the function, not assigning it
window.onload = checkIt();
Needs to be
window.onload = checkIt;
But do you really want to run the validation when the page loads? You probably do not need this line at all. Delete it!
You are not cancelling the submit event. Your function returns true or false, but you are not handling it.
<form action="#" method="post" id="form1" onsubmit="checkIt();">
Your form tag needs to be
<form action="#" method="post" id="form1" onsubmit="return checkIt();">
notice the return statement. That will cancel the submission.
What is submit()? The page is probably throwing an error which you would be able to see in the console. You need to tell it what to submit. That means referencing a form.
<img src="ok.gif" onclick="submit();" style="cursor: pointer;">
There is no method called submit() in your code. Maybe you want to call the form submission.
<img src="ok.gif" onclick="doucment.form1.submit();" style="cursor: pointer;">
You would probably be better off using input with type="image" to submit the form.
<input type="image" src="ok.gif" />
Using the input means no JavaScript is needed to submit the form. So remove the image tag and add the input element!
And finally you are reading the value of the form, not the input
var pass = document.form1.value;
You want the input!
var pass = document.form1.sn.value;
And it makes no sense why 1234 would fail, but all other things pass. Don't you have the logic wrong?
You need to learn how to debug, use the browser's console and learn to use console.log() to see the data. Set break points and walk through the code so you can inspect what is going on. JavaScript 101.