How do I prevent form fields from clearing out? - javascript

I have a form in an HTML page with a script that checks the fields in the form, the problem is that whenever I write something "wrong" in the field and the script gives an alert(), all the fields of the form clear out.
Here's the code:
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="style.css">
<link rel="icon" href="loginIcon.png">
<script src="script.js"></script>
</head>
<body>
<form id="form" method="POST">
<div class="center"><input type="text" placeholder="E-mail" id="email" name="email"></div>
<div class="center"><input type="password" placeholder="Password" id="pass" name="pass"></div>
<div><input type="checkbox" class="check" id="check"> I'm not a Robot</div>
<div class="center"><button onclick="check()">LOGIN</button></div>
Don't have an account yet? Sign Up
</form>
</body>
</html>
And the script:
function check() {
var em = document.getElementById("email").value.trim()
var ps = document.getElementById("pass").value.trim()
var ch = document.getElementById("check")
if (ch.checked) {
if (em == "" || em == undefined) {
alert("Email missing")
return false
} else if (ps == "" || ps == undefined) {
alert("Password missing")
return false
} else {
if (!em.includes("#")) {
alert("Missing '#'")
return false
} else if (ps.length > 16) {
alert("Password must be 16 characters or less")
return false
} else {
document.getElementById("form").action = "check.php"
}
}
} else {
alert("You're a Robot!")
return false
}
}

Change your form to this
<form id="form" action="check.php" method="POST" onsubmit="return check()">
<div class="center"><input type="text" placeholder="E-mail" id="email" name="email"></div>
<div class="center"><input type="password" placeholder="Password" id="pass" name="pass"></div>
<div><input type="checkbox" class="check" id="check"> I'm not a Robot</div>
<div class="center"><button type="submit">LOGIN</button></div>
Don't have an account yet? Sign Up
</form>
Right now, the form is submitted after the alert, you need to have this event on form submission so that in case of false, form submission is halted.
onsubmit receives a boolean (true by default) so if you return false from the function, the submission will be halted (as done here).

Related

form submit with setTimeout not working as expected [duplicate]

This question already has answers here:
javascript: validate form before submit?
(2 answers)
Closed 1 year ago.
I am submitting a form based on a condition and a setTimeout statement in submit event handler, however the form is still getting submitted even when I put return false in setTimeout function.
bool = true;
$('.form-example').submit(function(e) {
//some_stuff where I am get a value true or false in variable bool
setTimeout(function () {
if(bool) {
console.log('form shouldnt submit coz the following statement is return false');
return false;
}else{
return true;
}
}, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" class="form-example">
<div class="form-example">
<label for="name">Enter your name: </label>
<input type="text" name="username" id="username" required>
</div>
<input type="submit" name="submit_user">
</form>
You should use e.preventDefault() only when you don't want to submit form.
var bool = false;
$('.form-example').submit(function(e) {
//some_stuff where I am get a value true or false in variable bool
if(bool) {
alert('Not submit');
e.preventDefault();
return false;
} else {
alert('Submit');
return true;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" class="form-example">
<div class="form-example">
<label for="name">Enter your name: </label>
<input type="text" name="username" id="username" required>
</div>
<input type="submit" name="submit_user">
</form>
bool = false;
$('.form-example').submit(function(e) {
e.preventDefault();
//some_stuff where I am get a value true or false in variable bool
if(bool) {
alert('Not submit');
return false;
}else{
alert('Submit');
$(this).unbind("submit").submit();
return true;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" class="form-example">
<div class="form-example">
<label for="name">Enter your name: </label>
<input type="text" name="username" id="username" required>
</div>
<input type="submit" name="submit_user">
</form>

Having issues with field level validation using simple function

I am fairly new to coding so forgive me if it is something simple I am missing.
I am trying to validate the First Name field using a simple If statement in the function, but when I test it via live server the form submits without throwing the alert.
function validateForm() {
var firstName = document.getElementById('fname').value;
function firstNameValid() {
if (firstName == "") {
alert("First name empty")
return false;
} else {
return true;
}
};
firstNameValid(firstName);
};
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form name="registration" action="page2.html" onsubmit="return validateForm()" method="GET">
<ul>
<li>
<label for="fname">First Name:</label><br>
<input type="text" id="fname" name="fname" onsubmit="return firstNameValid(document.registration.fname)"><br>
</li>
<li>
<label for="lname">Last Name:</label><br>
<input type="text" id="lname" name="lname"><br>
</li>
<li>
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br>
</li>
<li>
<label for="phonenumber">Phone Number:</label><br>
<input type="text" id="phonenumber" name="phonenumber">
</li>
</ul>
<button type="submit" value="Submit">Submit</button>
</form>
<script>
src = "app.js"
</script>
</body>
</html>
The script should be loaded into the page like this…
<script src="app.js"></script>
…not like this…
<script>
src = "app.js"
</script>
validateForm doesn't return anything - you probably just need to change
firstNameValid(firstName);
to
return firstNameValid(firstName);
But, I'm a little rusty on when a form does / does not end up submitting, you may need to do
function validateForm(e) {
var firstName = document.getElementById('fname').value;
function firstNameValid() {
if (firstName == "") {
alert("First name empty")
e.preventDefault();
return false;
} else {
return true;
}
};
return firstNameValid(firstName);
};
<form name="registration" action="page2.html" onsubmit="return validateForm(event)" method="GET">

Why the form is getting submitted even if all the fields are empty?

Why my form is getting submitted even if I leave all fields empty. I can't figure out what the problem is. The if loops looks fine to me.
This is my code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Javascript form check</title>
</head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<body style="margin-top: 30px; margin-left: 30px;">
<form method="POST" action="form-handler" onsubmit="return checkForm(this);">
<p>First Name <input type="text" size="32" name="first_name"></p>
<p>Email Address <input type="text" size="32" name="email"></p>
<p>Phone Number <input type="number" size="32" name="phoneno"></p>
<p>Password <input type="password" size="32" name="pass"></p>
<p>Verify Password <input type="password" size="32" name="pass_verify"></p>
<p>Date of Birth <input type="date" size="32" name="date"></p>
<p>Weight <input type="text" size="32" name="weight"></p>
<input type="submit">
</form>
<script>
function checkForm(form) {
// validation fails if the input is blank
if (form.first_name.value == "") {
alert("Error: Input is empty!");
form.first_name.focus();
return false;
}
if (form.weight.length == 0)
{
alert("Invalid Weight");
return false;
}
// regular expression to match only alphanumeric characters and spaces
var re = /^[\w ]+$/;
// validation fails if the input doesn't match our regular expression
if (!re.test(form.first_name.value)) {
alert("Error: Input contains invalid characters!");
form.first_name.focus();
return false;
}
//Code to Validate Phone Number
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(!(form.phoneno.match(phoneno))
{
alert("Number must be 10 characters");
return false;
}
//Code to validate password
var passw= /^[A-Za-z]\w{4,14}$/;
if(!(form.pass.match(passw)))
{
alert('Wrong password')
return false;
}
//Code to validate email
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(form.email.value))){
alert("You have entered an invalid email address!")
return false;
}
}
</script>
</body>
</html>
you are missing a ) in this line
if(!(form.phoneno.match(phoneno)))
Your code was just riddled with errors so I've sorted most of them here :
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Javascript form check</title>
</head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<body style="margin-top: 30px; margin-left: 30px;">
<form method="POST" action="form-handler" onsubmit="return checkForm(this);" >
<p>First Name <input type="text" size="32" name="first_name"></p>
<p>Email Address <input type="text" size="32" name="email"></p>
<p>Phone Number <input type="number" size="32" name="phoneno"></p>
<p>Password <input type="password" size="32" name="pass"></p>
<p>Verify Password <input type="password" size="32" name="pass_verify"></p>
<p>Date of Birth <input type="date" size="32" name="date"></p>
<p>Weight <input type="text" size="32" name="weight"></p>
<input type="submit">
</form>
<script>
function checkForm(form) {
// validation fails if the input is blank
if (form.first_name.value === "") {
alert("Error: Input is empty!");
form.first_name.focus();
return false;
}
if (form.weight.length === 0) {
alert("Invalid Weight");
return false;
}
// regular expression to match only alphanumeric characters and spaces
var re = /^[\w ]+$/;
// validation fails if the input doesn't match our regular expression
if (!re.test(form.first_name.value)) {
alert("Error: Input contains invalid characters!");
form.first_name.focus();
return false;
}
//Code to Validate Phone Number
var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if (!(form.phoneno.match(phoneno))) {
alert("Number must be 10 characters");
return false;
}
//Code to validate password
var passw = /^[A-Za-z]\w{4,14}$/;
if (!(form.pass.match(passw))) {
alert('Wrong password')
return false;
}
//Code to validate email
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(form.email.value))) {
alert("You have entered an invalid email address!");
return false;
}
}
</script>
</body>
</html>
Working fiddle here : https://jsfiddle.net/chj8rpxv/1/
<body>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post" required>
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</body>

Trying to post data with form, and check input field if empty

I'm trying to have a form where I can search a database, but also have simple error handling where I can check if the user did not enter anything and run the function validateForm. However I'm not sure how to do both.
<form action="http://apsrd7252:5000/result/" method="POST">
<input type="text" id="IDSub" name="hostname" />
<input onclick="return validateForm()" type="submit" value="Submit" placeholder="Host Name" />
</form>
Here's the script
function validateForm() {
var a = document.getElementById("IDSub");
if( a.value == null) {
alert("Please fill in an ID");
return false;
} else {
window.location.href = "http://apsrd7252:5000/result";
}
}
Instead of "null" in if condition simply use empty string like "".
function validateForm() {
var a = document.getElementById("IDSub");
if( a.value == "") {
alert("Please fill in an ID");
return false;
} else {
window.location.href = "http://apsrd7252:5000/result";
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body>
<form action="http://apsrd7252:5000/result/" method="POST">
<input type="text" id="IDSub" name="hostname" />
<input onclick="return validateForm()" type="submit" value="Submit" placeholder="Host Name" />
</form>
</body>
</html>

JavaScript username and password verification

I am trying to take a username and password as input and if the entered username and password are admin admin I want to forward them to a new php file. I dont understand where I am going wrong. Any help. Thank you in advance
<html>
<head>
<script type="text/javascript">
function validate()
{
window.alert("called");
var user=document.getelementbyId(log).value;
var pass=document.getelementbyId(password).value;
window.alert("stored");
if((user=="admin")&&(pass="admin"))
{
window.alert("logging");
window.location.href='edusculpt_admin.php';
}
else
window.alert("Username or Password Incorrect");
}
</script>
</head>
<body>
<h3>Admin Login</h3>
<form method="post">
<p>
Login ID: <input type="text" id="log" value=""
placeholder="Username or Email">
</p>
<p>
Password: <input type="password" id="password" value=""
placeholder="Password">
</p>
<input type="submit" value="Login" onclick="validate()">
</form>
</body>
</html>
Javascript is case sensitive, getelementbyId should be getElementById and id's needs to be wrapped in quotes.
<script type="text/javascript">
function validate()
{
window.alert("called");
var user=document.getElementById('log').value;
var pass=document.getElementById('password').value;
window.alert("stored");
if((user=="admin")&&(pass=="admin"))
{
window.alert("logging");
window.location.href='edusculpt_admin.php';
}
else
window.alert("Username or Password Incorrect");
}
</script>
Also Note, You have submit button in your form .. which is not handled in validate function, either you can make <input type="button" ... or handle event in validate method.
getelementbyId should be getElementById & enclose the ID name by quote
var user=document.getElementById("log").value;
var pass=document.getElementById("password").value;
And compare by == instead of =
if((user=="admin")&&(pass=="admin"))
^^^
change onclick="validate()" to onclick="return validate();".
this way, when validate returns false, the form won't click. you'd also have to change the validate func to return false when the form doesn't validate, the resulting code would be:
<html>
<head>
<title>
User Validation : 2nd Program
</title>
<script type="text/javascript">
function validate()
{
alert(form.username.value)
alert(document.getelementbyId(username).value);
alert(form.password.value)
if(form.username.value == "sample" && form.password.value =="password")
{
alert("User Validated ");
return true;
}
else
{
alert("Incorrect Username or Password" );
return false;
}
}
</script>
</head>
<h3>Admin Login</h3>
<form method="post">
<p>
Login ID: <input type="text" id="log" value=""
placeholder="Username or Email">
</p>
<p>
Password: <input type="password" id="password" value=""
placeholder="Password">
</p>
<input type="submit" value="Login" onclick="validate()">
</form>
</body>
</text>
</body>
try this one
<script type="text/javascript">
function validate()
{
alert(form.username.value)
alert(document.getelementbyId(username).value);
alert(form.password.value)
if(form.username.value == "sample" && form.password.value =="password")
{
alert("User Validated ");
return true;
}
else
{
alert("Incorrect Username or Password" );
return false;
}
}
</script>
Update: continue and break illustrated.
while(true) {
// :loopStart
var randomNumber = Math.random();
if (randomNumber < .5) {
continue; //skips the rest of the code and goes back to :loopStart
}
if (randomNumber >= .6) {
break; //exits the while loop (resumes execution at :loopEnd)
}
alert('value is between .5 and .6');
}
// :loopEnd

Categories

Resources