I'm trying to delay the submission of a form but only when i trigger the submit after the delay it does not send the post values.
this is my html
<form id="form_anim" name="form" autocomplete="off" action="index.php" method="POST">
<input name="username" id="username" type="text" placeholder="Nome utente" autofocus required>
<input name="password" id="password" type="password" placeholder="Password" required>
Hai dimenticato la password?
<input id="invio" name="invio" type="submit" value="Accedi">
</form>
and this is the script
$('#form_anim').on('submit', function (event, force) {
if (!force) {
var $this = $(this);
event.preventDefault();
setTimeout(function () {
$this.trigger('submit', true);
}, 2000);
}
});
help me please.
This will effectively submit your form with a delay.
$('#form_anim').on('submit', function (e) {
var form = this;
setTimeout(function () {
form.submit();
}, 2000);
return false;
});
(btw, you don't need jQuery for this, unless you want to support IE8 and below)
Demo page
Monitor your network (via browser inspector) to see it in action
note sure if you meant to submit twice?
$('#form_anim').on('submit', function(event, force) {
if (!force) {
var $this = $(this);
setTimeout(function() {
event.preventDefault();
$this.trigger('submit', true);
}, 2000);
}
});
Try following code
It works smoothly
<form onsubmit="return delay('1')" id="form_anim" name="form" autocomplete="off" action="#" method="get">
<input name="username" id="username" type="text" placeholder="Nome utente" autofocus required>
<input name="password" id="password" type="password" placeholder="Password" required>
Hai dimenticato la password?
<input id="invio" name="invio" type="submit" value="Accedi"/>
</form>
Javascript
<script>
function delay(a){
if(a == 1){
setTimeout(delay(2),2000);
return false;
}
else{
$("#form_anim").submit();
}
}
</script>
I recommend you to use a button without type="submit":
<button id="send">Send</button>
$('#send').on('click', function(event) {
setTimeout(function() {
$('#form_anim').submit();
}, 2000);
});
Related
Trying to verify form input via a jQuery get request, but function does not get called.
Tried using just the jQuery (without function), the $.get works and returns proper values. I need the function approach to return false if (and stop form from submitting) if condition is not met.
<form onSubmit="return checkName();" action="/register" method="post">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
<script>
function checkName() {
$(document).ready(function () {
$("button").click(function () {
$.get("/check?username=" + document.getElementById('1').value, function (data, status) {
alert(data);
return false;
});
});
});
}
</script>
I expect the function to be called, return true if input verified (and go on with form submission) and false (stop form from submitting) if verification fails.
It isn't common practice to put events within the html anymore, as there is addEventListener. You can add it directly from the javascript:
document.querySelector('form').addEventListener('submit', checkName)
This allows for easier code to navigate, and makes it easier to read.
We can then prevent the form form doing it's default action by passing the first parameter to the function, and calling .preventDefault() as you can see from the modified function below. We no longer need to have return false because of it.
document.querySelector('form').addEventListener('submit', checkName)
function checkName(e) {
e.preventDefault()
$.get("/check?username=" + document.getElementById('1').value, function(data, status) {
alert(data);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/register" method="post">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
You're returning false from the async handler function. As such, that's not going to stop the form from being sent.
A better solution would be to always prevent the form from being submit then, based on the result of your AJAX request, submit it manually.
Also note that it's much better practice to assign unobtrusive event handlers. As you're using jQuery this is a trivial task. This also gets you access to the Event object which was raised by the form submission in order to cancel it. Try this:
<form action="/register" method="post" id="yourForm">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
$(document).ready(function() {
$("#yourForm").on('submit', function(e) {
e.preventDefault();
var _form = this;
$.get('/check', { username: $('#1').val() }, function(data, status) {
// interrogate result here and allow the form submission or show an error as required:
if (data.isValid) { // just an example property, change as needed
_form.submit();
} else {
alert("Invalid username");
}
});
});
});
You need to return from function not from inside the callback, and you do one if you assign to onsubmit you don't need click handler. And also click handler will not work if you have action on a form.
You need this:
function checkName() {
$.get("/check?username=" + document.getElementById('1').value, function(data, status){
alert(data);
});
return false;
}
this is base code, if you want to submit the form if data is false, no user in db then you need something like this (there is probably better way of doing this:
var valid = false;
function checkName() {
if (valid) { // if valid is true it mean that we submited second time
return;
}
$.get("/check?username=" + document.getElementById('1').value, function(data, status){
if (data) { // we check value (it need to be json/boolean, if it's
// string it will be true, even string "false")
valid = true;
$('form').submit(); // resubmit the form
}
});
return valid;
}
You can mark all your fields as required if they cannot be left blank.
For your function you may use the below format which works for me.
function checkName() {
var name = $("#1").val();
if ('check condition for name which should return true') {} else {
return false;
}
return true;
}
Just write the name of the function followed by (). no need to write return on onsubmit function call
function checkName()
{
$(document).ready(function(){
$("button").click(function(){
$.get("/check?username=" + document.getElementById('1').value, function(data, status){
alert(data);
return false;
});
});
});
}
<form onSubmit="checkName();" action="/register" method="post">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
I think if you replace button type from submit to button and then on button click event, inside get request, if your condition gets true, submit the form explicitly, would help you too achieve what you require.
You should remove the document.ready and the button event click.
EDITED
Adding an event parameter to checkName :
<form onSubmit="return checkName(event);" action="/register" method="post" id="myForm">
<div class="form-group">
<input id="1" autocomplete="off" autofocus class="form-control" name="username" placeholder="Username" type="text">
</div>
<div class="form-group">
<input class="form-control" name="password" placeholder="Password" type="password">
</div>
<div class="form-group">
<input class="form-control" name="passconf" placeholder="Confirm password" type="password">
</div>
<button id="2" class="btn btn-primary" type="submit" value="submit">Register</button>
</form>
<script>
function checkName(e){
e.preventDefault();
e.returnValue = false;
$.get("/check?username=" + document.getElementById('1').value,
function(data, status){
if(data) // here you check if the data is ok
document.getElementById('myForm').submit();
else
return false;
});}
</script>
I have three email forms on one page, all using the same class. When someone enters an email address and submits one of those forms, I want to validate the email address entered into that specific form. The problem that I'm having if is someone enters an email address for one of the later forms, it validates against the data in the first form. How can I make it so my validation function validates for the field into which the email address was entered without having to give each form a unique ID and have the validation code multiple times?
The validation code is below and code for one of the forms. Thanks!
<script>
function validateMyForm() {
var sEmail = $('.one-field-pardot-form-handler').val();
if ($.trim(sEmail).length == 0) {
event.preventDefault();
alert('Please enter valid email address.');
return false;
}
if (validateEmail(sEmail)) {
}
else {
event.preventDefault();
alert('Invalid Email Address. Please try again.'); }
};
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(sEmail)) {
return true;
}
else {
return false;
}
}
</script>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" method="post" onSubmit="return validateMyForm();" novalidate>
<input class="one-field-pardot-form-handler" maxlength="80" name="email" size="20" type="email" placeholder="Enter Email Address" required="required" />
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
Rather than calling the method from the html onsubmit attribute, wire the whole thing up in jquery.
$('form.myform').submit(function(e){
var $theForm = $(this);
var $theEmailInput = $theForm.find('.one-field-pardot-form-handler');
validateEmail($theEmailInput.val());
});
If you have 3 forms, just target the email field (via the class) within the context of the form.
And, don't use inline HTML event attributes (onsubmit, etc.), there are many reasons why and you can read about those here.
Instead, do all your event binding with JavaScript/JQuery and then you won't need to worry about return false to cancel the event if you are already using .preventDefault(). Additionally, it's best to capture the event reference as an argument to the event callback function, instead of the global event object.
There were other items that should be adjusted as well, so see additional comments inline:
// Get all the form elements and set up their event handlers in JavaScript, not HTML
$("form").on("submit", validateMyForm);
function validateMyForm(evt) {
// First, get the form that is being filled out
var frm = evt.target;
evt.preventDefault();
// Now, just supply the form reference as context for the email search
// Notice the extra argument after the selector "frm"? That tells JQuery
// where within the DOM tree to search for the element.
var sEmail = $('.one-field-pardot-form-handler', frm).val();
// Just to show that we've got the right field:
$('.one-field-pardot-form-handler', frm).css("background-color", "yellow");
// ***************************************************************************
// No need to convert a string to a JQuery object and call .trim() on it
// when native JavaScript has a .trim() string method:
if (sEmail.trim().length == 0) {
evt.preventDefault();
alert('Please enter valid email address.');
}
// Don't have empty branches, reverse the logic to avoid that
if (!validateEmail(sEmail)) {
evt.preventDefault();
alert('Invalid Email Address. Please try again.');
}
}
function validateEmail(sEmail) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
return filter.test(sEmail);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n"
method="post"
novalidate>
<input class="one-field-pardot-form-handler"
maxlength="80"
name="email"
size="20"
type="email"
placeholder="Enter Email Address"
required>
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
So a combination of #paul and #ScottMarcus' answers above ultimately got me to where I needed to go. Below is what I ended up with and it works as intended. As others have pointed out, I'm definitely a n00b and just learning javascript so certainly may not be perfect:
<script>
$('form.pardot-email-form-handler').submit(function(event) {
var theForm = $(this);
var theEmailInput = theForm.find('.one-field-pardot-form-handler');
var theEmailValue = theEmailInput.val();
function validateEmail(theEmailValue) {
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(theEmailValue)) {
return true;
} else {
return false;
}
}
if (!validateEmail(theEmailValue)) {
event.preventDefault();
alert('Invalid Email Address. Please try again.');
} else {
return true;
}
});
</script>
<div class="nav-email-form">
<form action="https://go.pardot.com/l/43312/2017-10-24/7dnr3n" method="post" class="pardot-email-form-handler" novalidate>
<input class="one-field-pardot-form-handler" maxlength="80" name="email" size="20" type="email" placeholder="Enter Email Address" required="required" />
<div style="position:absolute; left:-9999px; top: -9999px;">
<label for="pardot_extra_field">Comments</label>
<input type="text" id="pardot_extra_field" name="pardot_extra_field">
</div>
<button type="submit" name="submit">Submit</button>
</form>
</div>
This is the current situation, and the code is self explanatory.
Form Html
<form id="register" action="example.com/signup" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<input id="email" type="email" name="email">
<label for="email">Email</label><br />
<input id="password" type="password" name="password">
<label for="password">Password</label>
<button type="submit" name="register" id="submit" value="Submit">Submit</button>
</form>
Javascript
$('#register').submit(function(event){
event.stopPropagation();
event.preventDefault();
alert('fff');
if(condition)
{
$(this).submit();
}
else
{
//dostuff
if(condition)
{
//dostuff
return;
}
else
{
$(this).submit();
}
}
});
But the form submit goes into the loop, how do I prevent it from happening ?
This bit of code that you currently have will initiate your submit callback again
$(this).submit();
You don't want that - you just want to return true; if you want to proceed with the submission or return false; if you don't.
Also, you don't need this part
event.stopPropagation();
event.preventDefault();
I have form which need to be submited to another domain, like this:
<form id="myform" action="https://example.com" target="myiframe" method="POST">
<input type="text" name="email" value="">
<input type="text" name="name" value="">
<input type="text" name="phone" value="">
<input type="submit" name="submit" value="Submit">
</form>
And iframe:
<iframe style="display:none;" name="myiframe" src=""></iframe>
This work fine, but after submit form it stays filled.
So, how to clear (reset) form after submit?
Use an event-listener to trigger the submit and the clearing.
First, change the submit button to a regular button with a proper id (you should do the same to the other elements):
<input type="button" name="submitButton" id="submitButton" value="Submit" />
Then bind the event-listener to the button with JavaScript:
<script type="text/javascript">
document.getElementById('submitButton').addEventListener('click', function ()
{
handleTheForm;
}, false);
</script>
Wherea handleTheform is a method, defined accordingly:
<script type="text/javascript">
function handleTheForm()
{
document.forms[0].submit(); // Submit the form.
document.forms[0].reset(); // Clear the form.
}
</script>
Edit To handle the Enter button, simply add an event-listener for buttons and check which key is being pressed:
<script type="text/javascript">
document.addEventListener('keypress', function (e)
{
var key = e.which || e.keyCode;
var enterKey = 13;
if (key == enterKey)
{
handleTheForm;
}
});
</script>
Your final picture should look something like this:
<form id="myform" action="https://example.com" target="myiframe" method="POST">
<input type="text" name="email" id="email" value="" />
<input type="text" name="name" id="name" value="" />
<input type="text" name="phone" id="phone" value="" />
<input type="button" name="submitButton" id="submitButton" value="Submit" />
</form>
<script type="text/javascript">
function handleTheForm()
{
document.forms[0].submit(); // Submit the form.
document.forms[0].reset(); // Clear the form.
}
document.getElementById('submitButton').addEventListener('click', function ()
{
handleTheForm;
}, false);
document.addEventListener('keypress', function (e)
{
var key = e.which || e.keyCode;
var enterKey = 13;
if (key == enterKey)
{
handleTheForm;
}
});
</script>
You might have to tweek something a little but since I haven't manage to test this.
This solution is applicable to your problem
// code from answer with bind() transfered to plain javascript
function SubmitWithCallback(form, frame, successFunction) {
var callback = function () {
if(successFunction)
successFunction();
frame.removeEventListener('load', callback, false);
};
frame.addEventListener('load', callback, false);
form.submit();
}
You can easily achieve this using jQuery by
$("#formId").reset();
Hope this helps...
I have a html5 form with name, surname ect. The reason why I'm using a form is so that the user has to fill in everything, for that I'm using required. I want to save all the data in localStorage, for that I need to move the data to JavaScript.
How do access the data in JavaScript when the submit button is pressed while redirecting the user to another page?
This is the code:
Html5
<form id="TheForm" method="post">
<input type="text" id="Name" placeholder="*Förnamn" required >
<input type="text" id="Surname" placeholder="*Efternamn" required >
<input type="email" id="FirstEmail" placeholder="*e-postadress" autocomplete="on" required >
<input type="email" id="SecondEmail" placeholder="*Verifiera e-postadress" autocomplete="off" required >
<input type="text" id="Address" placeholder="*Adress" required >
<input type="submit" id="Submit" onclick="function()" value="Skicka">
</form>
var submit = function () {
window.localStorage.name = document.getElementById('Name').value;
// Save all the other fields
// You either return a non-false value here and let the form submit
// Or you return false and do a window.location change
};
window.onload = function () {
var form = document.getElementById('TheForm');
if (form.attachEvent) {
form.attachEvent('submit', submit);
} else {
form.addEventListener('submit', submit);
}
}
Try this
Java Script
function storeDetails() {
if(typeof(Storage)!=="undefined") {
localStorage.setItem('name', document.getElementById('Name').value));
//code to store other values will go here
} else {
alert('Your browser do not support local storage');
}
}
HTML
<form id="TheForm" method="post" onsubmit="javascript:storeDetails();" action=" ">
<input type="text" id="Name" placeholder="*Förnamn" required >
<input type="text" id="Surname" placeholder="*Efternamn" required >
<input type="email" id="FirstEmail" placeholder="*e-postadress" autocomplete="on" required >
<input type="email" id="SecondEmail" placeholder="*Verifiera e-postadress" autocomplete="off" required >
<input type="text" id="Address" placeholder="*Adress" required >
<input type="submit" id="Submit" onclick="function()" value="Skicka">
</form>