form submit with setTimeout not working as expected [duplicate] - javascript

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>

Related

How do I prevent form fields from clearing out?

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).

return false but submit

i try two way to solve this problem
<form method="post">
<input type="text" id="testId" name="testId" placeholder="Email" />
<button id="btnValidate" type="submit" onclick="return check();">subscribe</button>
</form>
and other way is
<form method="post" onsubmit="return check();">
<input type="text" id="testId" name="testId" placeholder="Email" />
<button id="btnValidate" type="submit">subscribe</button>
</form>
my js is
function check() {
var email = document.getElementById("testId").value;
var exptext = /^[A-Za-z0-9_\.\-]+#[A-Za-z0-9\-]+\.[A-Za-z0-9\-]+/;
if(exptext.test(email)==false){
alert("error");
document.addjoin.email.focus();
return false;
}else{
alert("complete");
return true;
}
}
alert show "error" but submit wrong email.
What did I do wrong?
<form method="post" id="form">
<input type="text" id="testId" name="testId" placeholder="Email" />
<button id="btnValidate" type="submit">subscribe</button>
</form>
<script>
let form = document.querySelector('#form');
form.addEventListener('submit', function(e) {
e.preventDefault();
check();
});
</script>
<script>
function check() {
let email = document.getElementById("testId").value;
let exptext = /^[A-Za-z0-9_\.\-]+#[A-Za-z0-9\-]+\.[A-Za-z0-9\-]+/;
if(exptext.test(email) === false){
alert("error");
document.addjoin.email.focus();
return false;
} else {
alert("complete");
return true;
}
}
</script>
This should work
You just need to remove the onclick="return check();"
Then you just need to add document.getElementById("btnValidate").onclick = check; to your js and it would work

Show alert (Text Field is empty) on submit Html/JavaScript

How to get an Alert on Submit when I left a TextBox empty And It Should Turn To the Next page on submit.
Must Reply,
Thank You.
You can try this :
HTML :
<form action="" method="POST" id="myForm">
<input id="myInput" type="text" />
<input type="submit" />
</form>
(Replace the action attribute by the url of your destination page, the one you call the "next page").
JS (without jQuery):
var myForm = document.querySelector('#myForm');
var myInput = document.querySelector('#myInput');
myForm.addEventListener('submit', function(pEvent) {
if(myInput.value === '') {
pEvent.preventDefault(); //Prevents the form to be sent
alert('Ho! Stop!');
//Do whatever you want
}
});
JS (with jQuery) :
var myForm = $('#myForm');
var myInput = $('#myInput');
myForm.on('submit', function(pEvent) {
if(myInput.val() === '') {
pEvent.preventDefault(); //Prevents the form to be sent
alert('Ho! Stop!');
}
});
Demo : http://jsfiddle.net/af9qvkmp/9/
Here is the demo, based on jQuery!
HTML
<form action="" method="POST" id="form">
<input id="input1" type="text" />
<input id="input2" type="text" />
<input id="input3" type="text" />
<input id="input4" type="text" />
<input id="input5" type="text" />
<input type="submit" />
</form>
JS
$(function() {
$('#form').on('submit', function(event) {
var isError = false;
$(this).find('input[type="text"]').each(function() {
if($(this).val() == '') {
console.log($(this));
isError = true;
return false;
}
});
if(isError) {
event.preventDefault();
alert("Got Error");
} else {
// Submit the form
}
});
});
In form tag write
<form action="" method="post" enctype="multipart/form-data" onsubmit="return checkform(this);">
This is your input field
<input type="text" name="reviewValue" value="" id='starRate2' required>
Javascript Code:
<script language="JavaScript" type="text/javascript">
function checkform ( form ){
if (form.reviewValue.value == "") {
alert( "Please choice your Rating." );
form.reviewValue.focus();
return false ;
}
return true ;
}
</script>

JavaScript return false form validation not working

Can you help me, when the validation fails my script should unhide an error message in a p tag and return false but instead my form submits. Can you see where my problem is?
function validate() {
if (document.emailForm.EMAIL_ADDRESS_.value.length==0) {
$('#errorNoAddress').fadeIn();
return false;
}
if (document.emailForm.EMAIL_ADDRESS_.value.length>0) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
var address = document.emailForm.email.value;
if(reg.test(address) == false) {
$('#errorInvalidAddress').fadeIn();
return false;
}
}
document.emailForm.submit();
return true;
}
<form id="emailForm" name="emailForm" action="http://domain.com/formhandler.php" method="post">
<p id="errorNoAddress" class="error">Please enter an e-mail address.</p>
<p id="errorInvalidAddress" class="error">Please enter a valid email address.</p>
<label for="EMAIL_ADDRESS_">E-mail</label>
<input type="hidden" id="QUICK_SIGN_UP" name="QUICK_SIGN_UP" value="" />
<input type="image" src="btn-submit.gif" value="Submit" onclick="validate();" />
</form>
try <input type="image" src="btn-submit.gif" value="Submit" onclick="return validate();" />

Form validation with Javascript function

I am trying to validate a form, to make sure that the user inputs a value into a textbox. Here's my Javascript:
var formValidation = function(a) {
if (document.getElementById(a).value == "") {
alert('Please fill out the ' + a + ' field');
return false;
}
else {
return true;
}
}
And here's the form:
<div id="cultdiv">
<form action="add.php" method="POST">
<span><input type="hidden" name="id" id="cultid"/>
<input type="text" onSubmit ="formValidation('culture')" name="name" id="culture"/>
<input type="hidden" name="type" value="culture" />
<input type="submit" value="add/update" /></span>
</form>
</div>
For some reason it doesn't stop the form from being submitted or give the alert message.
You forgot to return from your inline handler.
Also, <input>s don't have an onsubmit event; you probably meant to put that in the <form>.
slaks means something along these lines.
<script>
var formValidation = function() {
if (document.getElementById('culture').value == "") {
alert('Please fill out the culture field');
return false;
}
else {
return true;
}
}
<div id="cultdiv">
<form action="add.php" method="POST" onsubmit="return formValidation(this)">
<span><input type="hidden" name="id" id="cultid"/>
<input type="text" name="name" id="culture"/>
<input type="hidden" name="type" value="culture" />
<input type="submit" value="add/update" /></span>
</form>
</div>

Categories

Resources