This question already has an answer here:
Interaction between JQuery validation and form submit handler: Broken, or am I doing something wrong?
(1 answer)
Closed 8 years ago.
So I've got a form with onsubmit="SubmitForm()" and also a $().validate(). The problem is that when submit is clicked, the .validate() works, but SubmitForm() also runs. I'm a little confused, could someone help me out?
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.2.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#eclub').validate({ // initialize the plugin
rules: {
FirstName: {
required: true,
minlength: 2,
},
LastName: {
required: true,
minlength: 2
},
'Email Address': {
required: true,
email: true
},
Zip: {
required: true,
minlength: 2
},
DOB_Month: {
required: true,
minlength: 2,
},
DOB_Day: {
required: true,
minlength: 1
},
over18: {
required: true
}
}
});
});
function autoDMA() {
var zip_code = $('#zip_code').val();
$.ajax({
url: 'get_zipCode.php',
type: 'POST',
data: {zip_code:zip_code},
success:function(data){$('#dma_code').val(data);}
});
}
function SubmitForm()
{
if($("#emailDeals").is(':checked')){
document.forms['eclub'].action='http://cl.exct.net/subscribe.aspx';
document.forms['eclub'].target='_blank';
document.forms['eclub'].submit();
}
if($("#mobileDeals").is(':checked')){
document.forms['eclub'].action='/assets/waterfall/waterfall_rest.php';
document.forms['eclub'].submit();
}
return true;
}
</script>
<div id="" style="width:60%;">
<br/>
<!-- <form action="http://cl.exct.net/subscribe.aspx" id="eclub" method="post" onsubmit="return validateForm(this)" style="width:100%;"> -->
<form method="post" id="eclub" onsubmit="SubmitForm()">
<input name="thx" value="http://papamurphys.com/Deals/ThankYou" type="hidden">
<input name="dma" value="" type="hidden" id='dma-set' />
<input name="dma2" value="" type="hidden" />
<input name="MID" value="29115" type="hidden" />
<input name="lid" value="846154" type="hidden" />
<input name="lid" value="17516793" type="hidden" />
<input name="SubAction" value="sub_add_update" type="hidden" />
<input type="hidden" name="status" value="normal" />
<input name="Birthdate" value="" type="hidden" id="bday"/>
<div class="clearfix">
<label for="name"><span class="bold">First Name</span></label><br />
<input class="required" name="FirstName" type="text" placeholder="" />
</div>
<div class="clearfix">
<label for="name"><span class="bold">Last Name</span></label><br />
<input class="required" name="LastName" type="text" placeholder="" />
</div>
<div class="clearfix">
<label for="email"><span class="bold">Email</span></label><br />
<input class="required" name="Email Address" type="text" placeholder="" />
</div>
<div class="clearfix">
<label for="email"><span class="bold">Mobile Number</span></label><br />
<input class="required" name="MobileNumber" type="text" placeholder="" />
</div>
<div class="clearfix">
<span class="bold">Zip/Postal Code</span><br />
<input class="required zip" id="zip_code" name="PostalCode" type="text" onkeyup="autoDMA()" placeholder="" maxlength="5" size="5" />
</div>
<div class="clearfix">
<input class="zip" id="dma_code" name="DMACode" type="text" placeholder="" maxlength="5" size="5" style="display:none;" />
</div>
<div class="clearfix">
<span class="bold">Birthday</span><br />
<input class="month user required" name="DOB_Month" type="text" placeholder="MM" maxlength="2" style="width:48px;" />
<input class="day user required" name="DOB_Day" type="text" placeholder="DD" maxlength="2" style="width:48px;" />
</div>
<div class="clearfix">
<input class="age user" class="required" name="emailDeals" id="emailDeals" type="checkbox"/> Sign me up for email deals
</div>
<div class="clearfix">
<input class="age user" class="required" name="mobileDeals" id="mobileDeals" type="checkbox"/> Sign me up for mobile deals
</div>
<div class="clearfix">
<input class="age user" class="required" name="over18" id="over18" type="checkbox"/> I'm over 18
</div>
<input class="join-btn" type="submit" style="float:right;line-height:14px;cursor: pointer" onclick="pageTracker._trackPageview('Forms', 'Submit', 'eClubSignUp')" value="SUBMIT" />
<!--<input type="button" class="join-btn" value="" onclick="validateForm()" />-->
</form>
</div>
Why don't you use submitHandler callback in validate()?
$(".selector").validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
}
});
Anything you want to do when the form is valid, and you click the button, would be done inside the plugin's submitHandler option. (Not via an external function triggered by an inline handler)
$('#eclub').validate({
// rules and other options,
submitHandler: function (form) {
if ($("#emailDeals").is(':checked')) {
document.forms['eclub'].action = 'http://cl.exct.net/subscribe.aspx';
document.forms['eclub'].target = '_blank';
form.submit(); // submit the form // this is the default
}
if ($("#mobileDeals").is(':checked')) {
document.forms['eclub'].action = '/assets/waterfall/waterfall_rest.php';
form.submit(); // submit the form // this is the default
}
}
});
Working DEMO: http://jsfiddle.net/vbs32y9u/
As #Mike says Why you use SubmitForm()?
Anyway you can try this:
function SubmitForm()
{
if ($("#eclub").valid())
{
if($("#emailDeals").is(':checked')){
document.forms['eclub'].action='http://cl.exct.net/subscribe.aspx';
document.forms['eclub'].target='_blank';
document.forms['eclub'].submit();
}
if($("#mobileDeals").is(':checked')){
document.forms['eclub'].action='/assets/waterfall/waterfall_rest.php';
document.forms['eclub'].submit();
}
return true;
}
else
{
return false;
}
}
Related
I have two radio button like:
Field_One
Field_Two
When I check Field_One it will show First_Name, Last_Name field but when I check Field_Two it will show reference_id field.
But one thing if this reference_id comes from url
like myurl.com?reference_id=12345 then the radio field will auto selected and only reference field will show on form list.
My problem is when reference_id found on url Field_Two not showing it always showing Field_One on load found
Here is my snippet:
$(document).ready(function () {
$('input[type="radio"]').click(function () {
if ($(this).attr("value") == "Field_One") {
$(".Field_One").show();
$(".Field_Two").hide();
}
if ($(this).attr("value") == "Field_Two") {
$(".Field_Two").show();
$(".Field_One").hide();
}
});
$('input[type="radio"]').trigger('click'); // trigger the event
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="myfield" value="Field_One" checked/> Field_One
<input type="radio" name="myfield" value="Field_Two" /> Field_Two
<div class="Field_One">
<input type="text" name="first_name" placeholder="First Name" />
<br><br>
<input type="text" name="last_name" placeholder="Last Name"/>
</div>
<br>
<br>
<div class="Field_Two">
<input type="text" name="reference_no" placeholder="reference_no" />
</div>
try this:
$(document).ready(function () {
$('input[type="radio"]').click(function () {
if ($(this).attr("value") == "Field_One") {
$(".Field_One").show();
$(".Field_Two").hide();
}
if ($(this).attr("value") == "Field_Two") {
$(".Field_Two").show();
$(".Field_One").hide();
}
});
//$('input[type="radio"]').trigger('click'); // trigger the event
let url = new URL(window.location.href);
let reference_id = url.searchParams.get("reference_id");
if (reference_id == null) {
$(".Field_One").show();
$(".Field_Two").hide();
}else{
$(".Field_Two").show();
$(".Field_One").hide();
$(".Field_Two").find('input[name="reference_no"]').val(reference_id);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="myfield" value="Field_One" checked="true" /> Field_One
<input type="radio" name="myfield" value="Field_Two" /> Field_Two
<div class="Field_One">
<input type="text" name="first_name" placeholder="First Name" />
<br><br>
<input type="text" name="last_name" placeholder="Last Name" />
</div>
<br>
<br>
<div class="Field_Two">
<input type="text" name="reference_no" placeholder="reference_no" />
</div>
So I have a function that validates form inputs and I noticed I had many questions so I wanted to automate it instead of typing it manually. So I created a for loop that goes from 1 to 25 and it works. But I want to add the i to 'q' so I won't have to type 'q1', 'q2', 'q3'... But I just can't add them together.
Here's my code:
$(function () {
for (var i = 1; i <= 25; i++) {
console.log(i);
$('#form_validation').validate({
rules: {
'checkbox': {
required: true
},
'q' + i: {
required: true
}
},
highlight: function (input) {
$(input).parents('.form-line').addClass('error');
},
unhighlight: function (input) {
$(input).parents('.form-line').removeClass('error');
},
errorPlacement: function (error, element) {
$(element).parents('.form-group').append(error);
}
});
}
});
So I don't really know how and I hope you could help me.
You should use a class for this via jQuery.validator.addClassRules
$(function() {
var myform = $('#form_validation');
jQuery.validator.addClassRules("question", {
required: true
});
$.validator.messages.required = 'Well, we need to know';
var myvalidator = $('#form_validation').validate({
rules: {
'checkbox': {
required: true
}
},
highlight: function(input) {
$(input).parents('.form-line').addClass('error');
},
unhighlight: function(input) {
$(input).parents('.form-line').removeClass('error');
},
errorPlacement: function(error, element) {
$(element).closest('.form-group').append(error);
}
});
$("#dovalidate").on("click", function(e) {
myform.validate();
myvalidator.form();
});
});
.error {
background-color: #ffffdd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.js"></script>
<form id="form_validation">
<div class="form-group">
<div class="form-line">
<input name="question1" class="question" type="text" />
</div>
</div>
<div class="form-group">
<div class="form-line">
<input name="question2" class="question" type="text" value="I got this" />
</div>
</div>
<div class="form-group">
<div class="form-line">
<input name="question3" class="question" type="text" data-msg="WOOPS fill this field" />
</div>
</div>
<div class="form-group">
<div class="form-line">
<input name="question4" required class="question" type="text" />
</div>
</div>
<div class="form-group">
<div class="form-line">
<input name="question5" class="question" type="text" value="Just GREAT" />
</div>
</div>
<div class="form-group">
<div class="form-line">
<input name="question6" class="question" type="text" />
</div>
</div>
<div class="form-group">
<div class="form-line">
<input name="question7" class="question" type="text" data-msg="What?" data-msg="What?" />
</div>
</div>
<div class="form-line">
<input type="checkbox" name="needcheese" />
<input type="checkbox" name="needcheese" />
<input type="checkbox" name="needcheese" />
<input type="checkbox" name="needcheese" />
</div>
</form>
<button id="dovalidate">Validate this</button>
Basically, I want to prepend a div only if the div I'm prepending isn't already showing.
$(".loginForm").submit(function() {
var username = $("input.username").val();
var password = $("input.password").val();
var errorvisible = $("body").has(".alert.error");
if (!username || !password && errorvisible == false) {
$('body').prepend("<div class=\"error alert\">One or more field(s), have been left empty</div>");
setTimeout(function() {
$('.error.alert').fadeOut('1000', function() {
$('.error.alert').remove();
});
}, 6000);
event.preventDefault();
}
});
At the moment, I'm trying to make it so the jquery will only do the if empty if statement if the error isn't currently visible however it's not working...
<div class="pageCont">
<div class="title">
<h1>LetsChat</h1>
<h4>The new way of interaction.</h4>
</div>
<div class="login box">
<form method="POST" action="#" class="loginForm">
<input type="text" class="loginInput username" placeholder="Aquinas Email or Number" /><br>
<input type="password" class="loginInput password" placeholder="Password" /><br>
<div class="checkBox">
<input type="checkbox" id="checkBoxLink">
<label for="checkBoxLink">Remember Me</label>
Forgotten your password?
</div>
<input type="submit" value="Submit" class="login btn green" />
<input type="reset" value="Clear Fields" class="reset btn green" />
</form>
</div>
<div class="signup box">
<form method="POST" action="#" class="signupForm">
<input type="text" class="signupInput" placeholder="First Name" /><br>
<input type="text" class="signupInput" placeholder="Last Name" /><br>
<input type="text" class="signupInput" placeholder="Aquinas Email" /><br>
<input type="password" class="signupInput" placeholder="Password" /><br>
<input type="submit" class="purple btn signup" value="Sign Up Today!">
</form>
</div>
</div>
The below should work if I'm understanding your question correctly?
$(".loginForm").submit(function() {
var username = $("input.username").val();
var password = $("input.password").val();
var errorvisible = $("body").has(".alert.error").length;
if (!username || !password)
{
if(errorvisible == 0)
$('body').prepend("<div class=\"error alert\">One or more field(s), have been left empty</div>");
setTimeout(function() {
$('.error.alert').fadeOut('1000', function() {
$('.error.alert').remove();
});
}, 6000);
event.preventDefault();
}
});
I have used this type of code many times:
if(!$('#myFancyDiv').is(':visible')) {
//prepend or do whatever you want here
}
BTW just for clarity, this code checks if 'myFancyDiv' is not visible.
You can check whether the .error.alert elements exists, if so don't do anything else create a new one
$(".loginForm").submit(function() {
var username = $("input.username").val();
var password = $("input.password").val();
var errorvisible = $("body").has(".alert.error");
if (!username || !password && errorvisible == false) {
if (!$('.error.alert').length) {
$('body').prepend("<div class=\"error alert\">One or more field(s), have been left empty</div>");
setTimeout(function() {
$('.error.alert').fadeOut('1000', function() {
$(this).remove();
});
}, 6000);
}
event.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="POST" action="#" class="loginForm">
<input type="text" class="loginInput username" placeholder="Aquinas Email or Number" />
<br>
<input type="password" class="loginInput password" placeholder="Password" />
<br>
<div class="checkBox">
<input type="checkbox" id="checkBoxLink">
<label for="checkBoxLink">Remember Me</label>
Forgotten your password?
</div>
<input type="submit" value="Submit" class="login btn green" />
<input type="reset" value="Clear Fields" class="reset btn green" />
</form>
I've been experimenting with JQuery form validation, but haven't been able to get success/failure classes to be added once the validation has been complete.
Here is my code:
https://jsfiddle.net/5WMff/
<form method = "post" id = "signUpForm">
<div class="modal-body">
<div class="form-group">
<label for="firstName">First Name:</label>
<input type="text" class="form-control" name="firstName">
</div>
<div class="form-group">
<label for="surname">Surname:</label>
<input type="text" class="form-control" name="surname" >
</div>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" name="email">
</div>
<div class="form-group">
<label for="phoneNumber">Phone Number:</label>
<input type="phone" class="form-control" name="phoneNumber">
</div>
<div class="form-group">
<label for="postalCode">Home Postcode:</label>
<input type="text" class="form-control" name="postalCode">
</div>
<div class="checkbox">
<label><input type="checkbox" name = "acceptTCs">Accept Terms and Conditions</label>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn" data-dismiss="modal">Back</button>
<input type = "submit" name = "submit" class = "btn btn-success btn-large" value = "Submit" ></button>
</div>
</form>
JS:
$(document).ready(function () {
$('#signUpForm').validate({
rules: {
firstName: {
minlength: 2,
required: true
},
surname: {
required: true,
email: true
},
email: {
minlength: 2,
required: true
},
phoneNumber: {
minlength: 7,
required: true
}
},
highlight: function (element) {
$(element).closest('.form-group').removeClass('success').addClass('error');
},
success: function (element) {
element.text('OK!').addClass('valid')
.closest('.form-group').removeClass('error').addClass('success');
}
});
});
The validation (OK vs. more info required) is working fine, it's just failing to add the success/failure class as well. I know it's something obvious I've missed out, but have come to a bit of a dead end.
The effect I'm looking for is like here: http://jsfiddle.net/5WMff/
Thanks.
$.validator.setDefaults({
submitHandler: function() {
alert("submitted!");
}
});
Use submitHandler . Hope this will help you.
I am having some trouble having my password validation working, I think that the javascript is now correctly defined but I am not able to validate the form successfull as it keeps posting regardless of the errors.
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#model Models.ResetModel
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#close').click(function (event) {
closeAjax();
event.cancelBubble = true;
event.returnValue = false;
event.preventDefault();
event.stopPropagation();
});
});
$(document).ready(function () {
$("#resetForm").validate({
rules: {
password: {
require: true,
minlength: 6
},
confirmpassword: {
require: true,
minlength: 6,
equalTo: "#password"
}
},
messages: {
password: {
require: "You must enter a password!",
minlength: "Password must contain at least 6 characters"
},
confirmpassword: {
require: "You must enter a password confirmation!",
minlength: "Password must contain at least 6 characters",
equalTo: "Password and Password Confirmation fields do not match!"
}
}
});
});
here is the HTML:
<div class="form_container">
<div class="logo">
<img class="logo" src="#Url.Content("~/Content/SP_Logo_white.png")" alt="SmartPlant Cloud"/>
</div>
<div class="reset">
<h3>Password Reset</h3>
<div class="reset-help">
<p>Forgot your password? Use the form to change or reset your password.</p>
</div>
#using (Html.BeginForm("Reset", "Reset", new { qString = Model.QueryString, #id = "resetForm" } ))
{
<label for="reset">UserName:</label>
<input type="text" id="username" name="username" /><br />
<label for="password">New Password:</label>
<input type="password" id="password" name="password" /><br />
<label for="confirmpassword">Confirm Password:</label>
<input type="password" id="confirmpassword" name="confirmpassword" />
<p><input type="submit" id="submit" value="Submit" /></p>
}
</div>
You need to create the function to validate the form client side that will return a value "false" value if the data entered is incorrect, hence the from will not be submitted. This does NOT involve PHP it's to catch it before the PHP is loaded..
You can do validation checks also- server side as well.
function Validate()
{
//insert javascript validation check
return false;
}
<form onsubmit="return Validate();" action="your.php" method="post" name="your name" >
<label for="reset">UserName:</label>
<input type="text" id="username" name="username" /><br />
<label for="password">New Password:</label>
<input type="password" id="password" name="password" /><br />
<label for="confirmpassword">Confirm Password:</label>
<input type="password" id="confirmpassword" name="confirmpassword" />
<p><input type="submit" id="submit" value="Submit" /></p>
</form>
Hope this helps.