I have a form where I bound action with validation. Following is line of form which calls JavaScript check.
<form id="signup_form" method="post" action="javascript:check();">
I have following JavaScript:
function check(form){
flag = 0
doValidations();
if(flag==1){
return;
} else {
$('#signup_form').submit();
$('#signup_form').attr('action', 'NewSignupConfirm.php');
return false;
}
}
When I click on submit, it does all validation and even show message of else statement but do not submit form. Than I again click on submit button and it submits form. What is wrong with it? any suggestion.
<form id="signup_form" method="post" action="NewSignupConfirm.php" onsubmit="return check();">
function check(form){
flag = 0
doValidations();
if(flag==1){
return false;
} else {
return true;
}
}
You can try this below code
function check(form){
if(doValidations()){
return true;
} else {
return false;
}
}
You don't need to add flag variable just return true or false from doValidations method
Related
Here is my sample code:
<button onClick="CheckData()" type="submit">
I have some conditions in CheckData function:
if (5<6) {
warning = "sure?";
} else if (5>3) {
warning = "really?";
} else {
warning = '';
}
Then I check:
if (warning.length>0) {
return confirm(warning);
} else {
return true; //also tried false
}
So I need the confirm dialog for the first two conditions, otherwise, I don't want the dialog to be displayed.
Now, when one of the first two conditions are met, the confirm dialog pops up, but when I click on cancel, it still submits the form.
Any suggestions?
PS: This code is a demo and different from the real one. But the concept is the same.
You can pass in the event Object to the CheckData function and prevent the default action if the confirm returns false with event.preventDefault().
<form>
<button onClick="CheckData(event)" type="submit">Submit</button>
</form>
<script>
function CheckData(e){
var warning;
if (5<6) {
warning = "sure?";
} else if (5>3) {
warning = "really?";
} else {
warning = '';
}
if (warning.length>0) {
var con = confirm(warning);
if(con){
return true;
} else {
e.preventDefault();
return false;
}
} else {
return true;
}
}
</script>
You can also return the result of CheckData so the default action will be prevented if it returns false.
<form>
<button onClick="return CheckData()" type="submit">Submit</button>
</form>
<script>
function CheckData(){
var warning;
if (5<6) {
warning = "sure?";
} else if (5>3) {
warning = "really?";
} else {
warning = '';
}
if (warning.length>0) {
var con = confirm(warning);
return con;
} else {
return true;
}
}
</script>
Change your HTML to this:
<form onsubmit="return CheckData()">
<button type="submit" />
...
</form>
Explanation:
The onsubmit event handler is called when the form is submitted.
When the event handler returns false the submission is aborted.
I tried to delay for 10 sec before submit form like this but not work. It's will be still return true by not to delay.
<form class="form" method="post" action="" ENCTYPE = "multipart/form-data" onsubmit="return checkform(this);" >
<input type="submit" name="submit" value="OK">
</form>
<script language="JavaScript" type="text/javascript">
function checkform ( form )
{
var test = "1";
setTimeout(function(){
if(test != '0'){
return false;
}
else
{
return true;
}
}, 10000);
}
</script>
I want to know, how to delay on checkform using javascript ?
You must return to the checkForm function. A return inside a callback does not return to the outer function. Even if it did it must be immediate, not 10 seconds later
You could use a flag so you can call the function again inside the delay by submitting the form again
var allowSubmit = false;
function checkform(form) {
if (allowSubmit) {
return true;
} else {
var test = "1";
setTimeout(function() {
if (test === '1') {
// when validation passes resubmit with updated flag
allowSubmit = true;
form.submit();
}
}, 10000);
return false;
}
}
Here is a better way to do it if you have jQuery library included. In your case, the page gets submitted to itself and gets refreshed, so your 10 seconds get reset.
<form class="form" method="post" action="" enctype = "multipart/form-data" >
<input type="submit" name="submit" value="OK">
</form>
$(function(){
$("form").bind("submit", function(e){
e.preventDefault();
e.stopPropagation();
var test = "1";
setTimeout(function(){
if(test != '0'){
//return false;
alert("false");
}else{
alert("true")
//return true;
}
}, 10000);
});
});
So the problem here is that a submit request is has the same outcome as if you were to return something in a function.
For example if you had something like this:
function returnExplanation(){
return 0;
console.log("You will never see me");
}
You will never see the text in the console after the return.
A submit functions the same. although there are a few other ways to make this happen, I made a few adjustments to your code to achieve what you were looking for.
<form class="form" id="submitForm" method="post" action="" ENCTYPE = "multipart/form-data">
<input type="button" name="submit" value="OK">
</form>
<script language="JavaScript" type="text/javascript">
$(document).ready(function () {
$('#submitForm').on('click', function ()
{
var test = 1;
setTimeout(
function ()
{
if (test !== 0)
{
console.log("false");
return false;
} else
{
console.log("true");
return true;
}
}, 10000);
$('#submitForm').submit();
});
});
</script>
The first thing I did was give your form an "id". this allows jQuery (or javascript) to easily decipher exactly which element they should be communicating with.
Next, I removed your "onsubmit" attribute and added the appropriate jQuery to respond to the click event.
After that, I changed your button from a "submit" to a "button" type.
lastly, after the timeout, your form still submits with the line that reads:
$('#submitForm').submit();
I hope this helps you on your way to becoming a better HTML / jQuery programmer.
function SaleProduct() {
var CusId=$('#CusId').val();
$.get('customer-id.php?CusId='+CusId, function(data) {
if(data==0){
alert("Customer Id not valid.")
return false;
}
});
}
<form action="sales-edit-insert.php" method="post" onSubmit="return SaleProduct()">
<input type="text" name="CusId" id="CusId"/>
<!--Some input field here-->
<input type="submit" value="Submit"/>
</form>
return false; or e.preventDefault(); not working on above function when I submit the form. Form is submitted after showing an alert.
Your SaleProduct returns nothing(actually undefined).
You can stop immediate form sending with return false; inside of onsubmit attribute:
<form action="sales-edit-insert.php" method="post" onSubmit="SaleProduct(); return false;">
And later you can submit your form manually:
function SaleProduct() {
var form = ...;
var CusId=$('#CusId').val();
$.get('customer-id.php?CusId='+CusId, function(data) {
if(data==0){
alert("Customer Id not valid.")
return;
}
form.submit();
});
return false; // you can also move this statement to here from attribute
}
Most simple way to get form element is provide it into onsubmit:
<form action="sales-edit-insert.php" method="post" onSubmit="return checkCustomer(this)">
And js:
function checkCustomer(form) {
//code from above
return false;
}
You're using jQuery already so why bother with the onsubmit attribute. Try
<form action="sales-edit-insert.php" method="post" id="sale-product-form">
and
jQuery(function($) {
$('#sale-product-form').on('submit', function(e) {
e.preventDefault()
var form = this;
$.get('customer-id.php', $(form).serialize(), function(data) {
if (data == 0) {
alert('Customer Id not valid.')
} else {
form.submit() // submit normally
}
})
})
})
I have a form that I want to validate before the form submits, when I press the Submit button. I know I am supposed to use preventDefault but I am not sure how to use it correctly:
function validateName() {
var name = form.firstname.value;
if (name == "") {
document.getElementById("firstnameInvalid").style.visibility = "visible";
} else if (/[0-9]/.test(name)) {
document.getElementById("firstnameInvalid").style.visibility = "visible";
} else {
document.getElementById("firstnameInvalid").style.visibility = "hidden";
}
}
<form name="form" method="post" onsubmit="return validate(this)">
<p>First Name:
<input type="text" name="firstname" onblur="validateName()" onchange="validateName()" id="name" />
<span id="firstnameInvalid" style="color:red; visibility:hidden"> Name is Invalid </span>
</p>
You can stop the form by adding return statement to your validation code. onsubmit will stop the form submit when the function returns false.
your validate() must return a true or false value to it work with onsubmit="return validate(this)"
try something like
function validate(variable)
{
if(condition) //add a condition to validate
{
return false; //if condition are met, return false and do not submit
}
//you can create more than one condition following this logic.
return true; //if none of the conditions are met, he return true and submit
}
As others have said, returning false in your onsubmit callback will prevent the form from being submitted.
var form = document.getElementById( 'idgoeshere' );
form.onsubmit( function() {
// validate here
return false;
});
I have a submit button that redirects to another page if all the required fields are filled out.
<input type="submit" onclick="validateForm();redirect();" class="someClass" value="Submit" />
Right now when the button is clicked, it calls both functions. How do I get it to where it does not call redirect if validateForm returns false?
Here is the validateForm function if it helps:
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
}
}
<input type="submit" onclick="validateForm(); return false;" class="someClass" value="Submit" />
Change the input to the code above. Also change your function to reflect the code below.
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
}else {
redirect();
}
}
Add a onclick handler, say validateAndRedirect:
function validateAndRedirect()
{
if(validateForm())
{
redirect();
}
else
{
return false;
}
}
Add this to the button:
<input...onclick="validateAndRedirect()" ... >
This function will call validate(). If validation fails, will return false. This false will prevent the submit action of the button. If validation passes, it will call redirect.
Make the first function call the next one and add this to your HTML :
<input> type=button onclick="validateForm(); return false;" </input>
Putting 'return false' will prevent redirection and will give time for your function to execute.
function validateForm(){
var email = document.forms["form"]["Email"].value;
if(email == null || email == ""){
alert("Email must be filled out");
return false;
} else
redirect();
}
Additionally, I'd recommend to abstain from putting any code in your HTML. It is considered a "bad practice". However, if you still want to put your code, it'll be more appropriate to put it in the form as an "onsubmit" action:
<form onsubmit="validateForm()">
If you want the function to execute when the submit button is clicked, you can just add an event listener in your script and an id to your button, like this:
var button = document.getElementById("submit");
button.onclick = function validateForm() { /*same code as above..*/ };
Hope it helps!