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>
Related
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>
So I have the following form, with an ajax, which to call the server for user authentication. Now the problem is that let's say the user password is wrong. If the user tries to correct it any subsequent call does no longer trigger the on('submit') function thus he is stuck at the page. How can I make it to allow resubmition of the form?
var login_email = document.getElementById("login_email");
var login_password = document.getElementById("login_password");
$(function() {
$('form#login_form').on('submit', function(e) {
console.log("submit");
$.post('/auth_user', $(this).serialize(), function (data) {
console.log(data);
if(data == "No user registered with this email.") {
login_email.setCustomValidity(data);
} else if(data == "Incorrect password.") {
login_password.setCustomValidity(data);
} else {
}
});
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/dashboard" id="login_form" method="post">
<div class="field-wrap">
<label>
Email Address<span class="req">*</span>
</label>
<input type="email" name="email" id="login_email" required autocomplete="off"/>
</div>
<div class="field-wrap">
<label>
Password<span class="req">*</span>
</label>
<input type="password" name="password" id="login_password" required autocomplete="off"/>
</div>
<p class="forgot">Forgot Password?</p>
<button class="btn btn-primary"/>Log In</button>
</form>
Answer... from discussion above.
Move the credential authentication ajax to the onchange event for both email and password and set a customvalidation message to "invalid username or password" or "" depending on ajax result.
Can you try adding a type submit attribute to your html button tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/dashboard" id="login_form" method="post">
<div class="field-wrap">
<label>
Email Address<span class="req">*</span>
</label>
<input type="email" name="email" id="login_email" required autocomplete="off"/>
</div>
<div class="field-wrap">
<label>
Password<span class="req">*</span>
</label>
<input type="password" name="password" id="login_password" required autocomplete="off"/>
</div>
<p class="forgot">Forgot Password?</p>
<button class="btn btn-primary" type="submit"/>Log In</button>
</form>
Also you need not put a listener for submit you can use the .submit() function of jquery
$(function() {
$('form#login_form').submit(function(e) {
console.log("submit");
$.post('/auth_user', $(this).serialize(), function (data) {
console.log(data);
if(data == "No user registered with this email.") {
login_email.setCustomValidity(data);
} else if(data == "Incorrect password.") {
login_password.setCustomValidity(data);
} else {
}
});
e.preventDefault();
});
});
The other way is you put a click handler on the button and internally call the .submit() for the form
I want to perform validation before any other onsubmit actions. Unfortunately, I have no control over the value of the onsubmit attribute on the form. So for example:
<form id="myForm" onsubmit="return stuffICantChange()"></form>
I've tried the following code, and several other methods, with no luck:
$("#myForm").onsubmit = function() {
console.log("hi");
}
Any help is appreciated, thanks.
If this is a duplicate, please let me know before marking it as such so that I can refute the claim if necessary.
EDIT:
My code as requested:
<form id="form_ContactUs1" name="form" method="post" action="index.php" onsubmit="return Validator1(this) && ajaxFormSubmit(this); return false">
<div class="form">
<div class="form-staticText">
<p>We look forward to hearing from you! Please fill out the form below and we will get back with you as soon as possible.</p>
</div>
<div class="form-group">
<input class="form-control" placeholder="Name" id="IDFormField1_Name_0" name="formField_Name" value="" size="25" required="" type="text">
<span class="form-control-feedback"></span>
</div>
<div class="form-group">
<input class="form-control" placeholder="Email" id="IDFormField1_Email_0" name="formField_Email" value="" size="25" required="" type="email">
<span class="form-control-feedback"></span>
</div>
<div class="form-group">
<input class="form-control bfh-phone" data-format="ddd ddd-dddd" placeholder="Phone" id="IDFormField1_Phone_0" name="formField_Phone" value="" size="25" type="tel">
<span class="form-control-feedback"></span>
</div>
<div class="form-group">
<textarea class="form-control" placeholder="Comments" name="formField_Comments" id="IDFormField1_Comments_0" cols="60" rows="5" required=""></textarea>
<span class="form-control-feedback"></span>
</div>
<div class="row submit-section">
<input name="submit" class="btn btn-success submit-button" value="Submit" type="submit">
</div>
</div>
$( "form" ).each(function() {
console.log( $(this)[0] );
sCurrentOnSubmit = $(this)[0].onsubmit;
$(this)[0].onsubmit = null;
console.log( $(this)[0] );
$( this )[0].onsubmit( function() {
console.log( 'test' );
});
});
You should be able to add unobtrusively another onsubmit function to #myForm, in addition to the function which already executes:
function myFunction() {
...
}
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit',myFunction,false);
Try
$("#myForm").submit(function(){
.. Your stuff..
console.log("submit");
return false;
});
This will trigger everytime the form is submitted then the end return false stops the forms default actions from continuing.
Try this, it is plain Javascript:
function overrideFunction(){
console.log('Overrided!');
}
var form;
form = document.querySelector('#myForm');
form.setAttribute('onsubmit','overrideFunction()');
Regards.
You should trigger a change event on every field in the form to check on validation.
$('input').on('change', function(e) {
if($(this).val() == '') {
console.log('empty');
}
});
This wil help the user mutch faster then waiting for the submit.
You could also try a click event before the submit.
$('#formsubmitbutton').on('click', function(e) {
//your before submit logic
$('#form').trigger('customSubmit');
});
$('#form').on('customSubmit', function(e) {
//your normal submit
});
Try this code:
$("#myForm").on('submit',function() {
console.log("hi");
});
Stumbling across this post and putting together other javascript ways to modify html, I thought I would add this to the pile as what I consider a simpler solution that's more straight forward.
document.getElementById("yourFormID").setAttribute("onsubmit", "yourFunction('text','" + Variable + "');");
<form id="yourFormID" onsubmit="">
....
</form>
i'm working with the forms and i want when i hit the submit buttom only that field gets red which are empty . don't knw how to fix it . if anyone can help me i'm new javascript and jquery thanks
My HTML
<form id="form">
<div class="form-group">
<label>Username</label>
<p><span id="usernameError"></span></p>
<input type="text" class="form-control" id="username" placeholder="Username">
</div>
<div class="form-group">
<label>Email</label>
<p><span id="emailError"></span></p>
<input type="email" class="form-control" id="email" placeholder="email">
</div>
<div class="form-group">
<label>Password</label>
<p><span id="passwordError"></span></p>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<div class="form-group">
<label>Confirm Password</label>
<p><span id="confPasswordError"></span></p>
<input type="password" class="form-control" id="confPassword" placeholder="Confirm Password">
</div>
<p><span id="warning"></span></p>
<button type="submit" id="submit" class="btn btn-default">Submit</button>
</form>
MY JAVASRIPT
now here is the situation . i put all the variables in one if statement and that's why they all are turning into red
$("#form").submit(function(){
if(password.val() != confPassword.val() )
{
alert("password dont match");
}
if($(this).val() == ""){
username.addClass("border");
email.addClass("border");
password.addClass("border");
confPassword.addClass("border");
// warning message
message.text("PLEASE FILL OUT ALL THE FIELDS").addClass("boldred");
// errors rendering
usernameError.text("username must be defined").addClass("red");
emailError.text("email must be valid and defined").addClass("red");
passwordError.text("password must be defined").addClass("red");
confPasswordError.text("confirm password must be matched and defined").addClass("red");
// disabling submit button
submit.attr("disabled" , "disabled");
return false;
}
else{
return true;
}
});
Try JQuery Validation Engine. Its very easy to implement your form.
Validation Engine
Supported for all browsers
First try adding required to all the necessary fields, like:
<input type="text" class="form-control" id="username" placeholder="Username" required>
Then disable (or delete) the if clause.
If that doesn't work, just let me know in the comments and I'll update the answer.
You are approaching the problem in incorrect way.
On Form submit you need to check each field you want separately.
For example:
$("#form").on('submit', function() {
var submit = true;
$(this).find('span').removeClass('red');
$(this).find('input').each(function() {
if ($.trim($(this).val()) === '') {
submit = false;
$(this).parents('.form-group').find('span').addClass('red');
}
});
return submit;
});
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);
});