How to disable submit button after click submit button - javascript

I have created forms using php and using jquery for validation.What i exactly need is if validation successful on submit button, disable the submit button till submission gets over.Here is my code:
if(document.location.pathname == "/contact-us"){
$("#form-contact-user").validate({
ignore: [],
rules: {
name:{
required: true
},email: {
email: true
},
phne: {
phnDash: true
},
zip: {
zipcode: true
}
},
errorPlacement: function(error, element) {
if (element.attr("type") == "checkbox") {
error.appendTo( element.parent().parent().parent(".form-checkboxes"));
}
else if (element.attr("name") == "mailing_address")
{
error.appendTo(element.parent().parent().parent());
}
else{
error.insertAfter(element);
}
}
});

Try this:
$('#btnId').attr('disabled', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" id="btnId" value="Submit">

I hope this is what you are looking for,
$('#submitBtn').click(function(event) {
//event.preventDefault();
$(this).attr('disabled', true);
//Perform Validation
//if(valid) {
// $("#form-contact-user").submit();
//}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" id="submitBtn" value="Submit">

According to the documentation you can use:
submitHandler (default: native form submit):
Callback for handling the actual submit when the form is valid.
ANSWER UPDATED
From your comment:
Getting the following error:-Uncaught TypeError: Cannot read property 'call' of undefined
This message depends on your rules. Because I don't know anything about your
html I can also assume a possible structure in the following snippet:
$("#form-contact-user").validate({
debug: true,
rules: {
name: {
required: true,
minlength: 2
},
email: {
required: true
},
phone: {
required: true
},
zip: {
required: true
}
},
errorPlacement: function (error, element) {
if (element.attr("type") == "checkbox") {
error.appendTo(element.parent().parent().parent(".form-checkboxes"));
}
else if (element.attr("name") == "mailing_address") {
error.appendTo(element.parent().parent().parent());
}
else {
error.insertAfter(element);
}
},
submitHandler: function(form) {
// do other things for a valid form
$(form).find(':submit').prop('disabled', true);
setTimeout(function() {
form.submit();
}, 1000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<form id="form-contact-user" method="get" action="">
<fieldset>
<legend>Please provide your name, email address, phone number and zipcode</legend>
<p>
<label for="name">Name (required, at least 2 characters)</label>
<input id="name" name="name" type="text">
</p>
<p>
<label for="email">E-Mail (required)</label>
<input id="email" type="email" name="email">
</p>
<p>
<label for="phone">Phone Number (required)</label>
<input id="phone" type="text" name="phone">
</p>
<p>
<label for="zip">Zip code (required)</label>
<textarea id="zip" name="zip"></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>

Related

How can I add operator ternary on jQuery validate?

My html code like this :
<form class="validatedForm" id="commentForm" method="get" action="">
<fieldset>
<input name="password" id="password" />
<input name="password_confirmation" />
</fieldset>
</form>
<button>Validate</button>
My JavaScript code to validate with jQuery validate like this :
jQuery('.validatedForm').validate({
rules: {
"password": {
minlength: 6
},
"password_confirmation": {
minlength: 6,
equalTo : "#password"
}
},
messages: {
"password": 'Please enter a password, minimal 6 characters',
"password_confirmation": 'Please confirm your password'
},
});
Demo and full code like this : http://jsfiddle.net/oscar11/fEZFB/609/
I want to add condition in jQuery validate
If password filled, required: true on password_confirmation
If password not filled, required: false on password_confirmation
Seems I need to add operator ternary on rules password_confirmation. But I'm still confused
How can I do it?
I try to make an answer for your problem, check this out
$(document).ready(function() {
$('.validatedForm').validate({
rules: {
"password": {
minlength: 6,
},
"password_confirmation": {
minlength: 6,
required: function(element) {
return $("input[name=password]").val() != "";
},
equalTo : "#password"
}
},
messages: {
"password": 'Please enter a password, minimal 6 characters',
"password_confirmation": 'Please confirm your password'
},
});
$('button').click(function () {
console.log($('.validatedForm').valid());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.11.1/jquery.validate.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.11.1/additional-methods.js"></script>
<form class="validatedForm" id="commentForm" method="get" action="">
<fieldset>
<input name="password" id="password" />
<input name="password_confirmation" />
</fieldset>
</form>
<button>Validate</button>

enable submit button when jquery.validate has valiated the form

I have a form that is being validated using jquery.validate.
I have added in reCAPTCHA 2.0 and this is being validated also.
However I want the form's submit button to be disabled untill the form is valid and this is where I am stuck.
The button is disabled but is not being enabled after the entries and captcha are all validated.
This is my form code
<div class="contact-Form">
<form id="form">
<label for="name">Name</label><br>
<input name="firstname" type="text" id="firstname" class="inputbox" value="" placeholder="Your name...">
<br><br>
<label for="name">Email</label><br>
<input name="email" type="email" id="email" class="inputbox" value="" placeholder="Your email address...">
<br><br>
<label for="name">Message</label><br>
<textarea class="messagebox" rows="10" cols="20" name="message" id="message" value="" placeholder="Your message..."></textarea>
<br><br>
<input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha">
<div class="g-recaptcha" data-sitekey="6LcjETAUAAAAAPC7-qXZW4xI89k1EhUzPWnD5mAP" data-callback="recaptchaCallback"></div>
<input type="hidden" class="hiddenRecaptcha required" name="hiddenRecaptcha" id="hiddenRecaptcha">
<br><br>
<button id="submit" disabled="disabled" type="submit">Submit</button>
</form>
</div>
And my javascript
$().ready(function() {
$("#form").validate({
ignore: ".ignore",
rules: {
"firstname": {
required: true,
minlength: 3
},
"email": {
required: true,
email: true
},
"message": {
required: true
},
"hiddenRecaptcha": {
required: function() {
if(grecaptcha.getResponse() == '') {
return true;
} else {
return false;
}
}
}
},
messages: {
"firstname": {
required: "<br/> You have not entered a name!",
minlength: "<br/> Your name must consist of atleast 3 characters",
},
"email": {
required: "<br/> You have not entered an email address!",
email: "<br/> Please use a valid email address!",
},
"message": {
required: "<br/> You have not entered a message!",
}
}
});
$('#form input').on('keyup blur click', function () { // fires on every keyup & blur
if ($('#form').valid()) { // checks form for validity
$('button.btn').prop('disabled', false); // enables button
} else {
$('button.btn').prop('disabled', 'disabled'); // disables button
}
});
});
function recaptchaCallback() {
$('#hiddenRecaptcha').valid();
};
Edit
I have changed this function
$('#form input').on('keyup blur click', function () { // fires on every keyup & blur
if ($('#form').valid()) { // checks form for validity
$('button.btn').prop('disabled', false); // enables button
} else {
$('button.btn').prop('disabled', 'disabled'); // disables button
}
});
To this
$('#form input').bind('keyup blur click', function () {
if ($(this).validate().checkForm()) {
$('#submit').removeClass('button_disabled').attr('disabled', false); // enables button
} else {
$('#submit').addClass('button_disabled').attr('disabled', true); // disables button
}
});
It now enables the button when any input is valid. I want it to only enable the button when all inputs are valid.
Can someone point out where I am going wrong please I have checked other posts which is how I managed to get this working up till this point
You can try by removing the disabled attribute from your input btn
example:
$("button.btn").removeAttr("disabled");
Hope this helps you.

Hide success and error messages on form

I have one subscription form with ajax. The problem is that success and error messages are always on the page. Why they are on the page and how to hide them until form is submitted?
This is my js function
$(document).ready(function(){
(function($) {
"use strict";
// validate subscribeForm form
$(function() {
$('#subscribeForm').validate({
rules: {
name: {
required: true,
minlength: 4
},
email: {
required: true,
email: true
}
},
messages: {
name: {
required: "Please enter your name?",
minlength: "Your name must consist of at least 4 characters"
},
email: {
required: "Please enter your email address"
}
},
submitHandler: function(form) {
$(form).ajaxSubmit({
type:"POST",
data: $(form).serialize(),
url:"subscribe.php",
success: function() {
$('#subscribeForm :input').attr('disabled', 'disabled');
$('#subscribeForm').fadeTo( "slow", 0.15, function() {
$(this).find(':input').attr('disabled', 'disabled');
$(this).find('label').css('cursor','default');
$('#sub_success').fadeIn();
});
},
error: function() {
$('#subscribeForm').fadeTo( "slow", 0.15, function() {
$('#sub_error').fadeIn();
});
}
})
}
})
})
})(jQuery)
})
And this is the form
<div class="footer-newsletter row footer-widget right-box">
<h3 class="footer-title">newsletter sign up</h3>
<form class="form-inline newsletter-form" id="subscribeForm" method="post" action="">
<input type="text" id="name" name="name" class="form-control" placeholder="Name">
<input type="email" id="email" name="email" class="form-control" placeholder="Email">
<button type="submit" class="btn btn-primary" name="sub_submit">Submit</button>
</form>
<div id="sub_success">You subscribe succesfully!</div>
<div id="sub_error">Opps! There is something wrong. Please try again</div>
</div>
So sub_success and sub_error are always on the page..
Change this following things in your code:-
<div id="sub_success" style="display:none">You subscribe succesfully!</div>
<div id="sub_error" style="display:none">Opps! There is something wrong. Please try again</div>
use this type alert it will gone in 3sec
$('#success_message').fadeIn(1000).html("<div class='alert alert-danger' role='alert' style='font-size: 15px;'>Soory some there is some error,please enter again data...</div>").fadeOut(3000);
Just add .hide on document.ready for both elements as below:
$(document).ready(function(){
$('.sub_success,.sub_error').hide();
});
You could just write a css
#sub_success, #sub_error {display:none}
then with jquery you can just show and hide by using
$("#sub_success").show();
$("#sub_error").hide();

Navigation between html pages on form validation

Working on static pages only.. no backend is present...Hi trying to navigate between html pages, and succeesful in that. But need to switch the page only when the form is properly validate, have tried but its not working..
Need some help...
HTML:
<div class="formContainer">
<form class="form" id="loginForm">
<div class="form-group">
<label>Login</label>
</div>
<div class="form-group">
<label for="loginForm-email">Email address</label>
<input type="email" class="form-control" id="loginForm-email" name="loginForm-email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="loginForm-password">Password</label>
<input type="password" class="form-control" id="loginForm-password" name="loginForm-password" placeholder="Password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
JS:
$(document).ready(function () {
var fnValidate = $("#loginForm").validate({
rules: {
"loginForm-email": {
required: true,
email: true
},
"loginForm-password": {
required: true,
minlength: 5
}
}
});
$('.btn').click(function(e) {
e.preventDefault();
if(fnValidate){
window.location.reload(true);
window.location.href = '../html/userPage.html';
}
else{
alert('hia');
}
});
});
The jQuery validator has custom success and failure callbacks which you can use.
As per your current approach, the fnValidate will return you an object. So you won't know whether it's validated or not. So try using the following approach.
$(document).ready(function () {
$("#loginForm").validate({
rules: {
"loginForm-email": {
required: true,
email: true
},
"loginForm-password": {
required: true,
minlength: 5
}
},
submitHandler: function () {
console.log("inside valid");
window.location.reload(true);
window.location.href = '../html/userPage.html';
// this.submit()
},
invalidHandler: function (event, validator) {
// 'this' refers to the form
console.log("Please fill the form");
}
});
});
jsfiddle example : http://jsfiddle.net/mohamedrias/2vvaN/2/
submitHandler is called only if the form is valid. So there you can submit the form.

Why does the JQuery valid() method always return True?

I have a simple HTML form:
<form id="frmNewCategory">
<span>New Category Name:</span>
<input type="text" id="txtNewCategoryName">
<label>Amount:</label>
<input type="text" id="txtNewCategoryAmount">
<br>
<input type="submit" value="Create" class="importantButton button" id="btnNewCategory">
<input type="button" value="Cancel" class="button" id="btnCancelNewCategory">
</form>
And a bit of jQuery-driven JavaScript using the validation plugin that fires when btnNewCategory is clicked:
function onNewCategoryClick(event)
{
$("#frmNewCategory").validate(
{
rules:
{
txtNewCategoryName : { required: true },
txtNewCategoryAmount : { required: true, number: true }
},
messages:
{
txtNewCategoryName : { required: "*" },
txtNewCategoryAmount: { required: "*", number: "Invalid Amount." }
}
});
if (!$("#frmNewCategory").valid())
return;
event.preventDefault();
var cmd = cmdFactory.createUndoableNewCategoryCommand($(this));
cmdBus.handleCommand(cmd);
}
The method above is supposed to validate frmNewCategory. Trouble is that even if the form has invalid values or no values at all the .valid() method still returns True.
Any ideas? What am I doing wrong?
The rules take form input "names" not "ids":
<input type="text" name="txtNewCategoryName" />
<input type="text" name="txtNewCategoryAmount" />
Instead of:
<input type="text" id="txtNewCategoryName">
<input type="text" id="txtNewCategoryAmount">
Use:
<input type="text" name="txtNewCategoryName">
<input type="text" name="txtNewCategoryAmount">
This pattern worked for me before:
$(".required").filter(function () { return $(this).val() == ""; }).addClass("invalidInput");
if (this.formWrp.valid() && this.formWrp.find(".invalidInput").length == 0)
return true;
After doing so, it seems that validation is activated.

Categories