JQuery Validate - Add/remove error css class in the form - javascript

I want to add/remove the error css class in the form.
$("#my-form").validate({
invalidHandler: function (event, validator) {
// 'this' refers to the form
var errors = validator.numberOfInvalids();
if (errors) {
$(this).addClass("error");
} else {
$(this).removeClass("error");
}
},
});
Problem with this approach:
When I use $("#my-form").validate().form() to validate the form, it will automatically add/remove the error css-class to each of the controls such as an input. By adding invalidHandler this additionally will add/remove the error css-class of the whole form.
Once I do validator.resetForm() to clear the messages, this will reset the css-class from the children controls but not from the form. I wish it automatically removes the css-class from the form by using a binding or any other sort of handler that trigger this action (removing the css-class from the form).
How I can fix this problem?
Source: http://jqueryvalidation.org/validate/
Update
Here a silly example: http://jsfiddle.net/F2Re4/ and I manually remove the class (in this example, I called the class: 'error-form')

Looking at the markup of your jsFiddle,
<input type="button" onclick="validate()" value="Validate"></input>
<input type="button" onclick="resetForm()" value="Reset Form"></input>
1) input elements do not have a closing tag. They may or may not need to be "self-closing" depending on your doctype, but there is never any such thing as an </input> tag.
2) Inline JavaScript is ugly and unnecessary when you use jQuery. onclick handlers can easily be removed and replaced with jQuery .on('click')...
$('#reset').on('click', function () {
var form = $("#myForm");
form.validate().resetForm();
});
3) You do not need a validate function attached to your "validate" button. Simply change the button into a type="submit" and it will be validated automatically. Otherwise, you would need another .on('click') handler and a .valid() within to trigger a validation test.
<input type="submit" id="validate" value="Validate" />
<input type="button" id="reset" value="Reset Form" />
Quote OP:
... validator.resetForm() to clear the messages, but this invalidHandler is never called and the 'error' css class still there in the form.
As per documenation, invalidHandler is only called when the form is invalid. If you reset the form, the form is no longer invalid. Therefore, the logic used within your invalidHandler is flawed.
var errors = validator.numberOfInvalids();
if (errors) {
$(this).addClass("form-error");
} else {
// this will never be called because invalidHandler
// is never called when there are no form errors
//$(this).removeClass("form-error");
}
There is nothing in this plugin that will automatically add/remove the class of the <form> element itself. The plugin only automatically adds/removes classes from the various data input elements. Therefore, if you manually add a class to the <form> element, then you're going to have to manually remove it when you reset the form.
$(document).ready(function () {
$("#myForm").validate({
// your rules & options
});
$('#reset').on('click', function () {
var form = $("#myForm");
form.validate().resetForm(); // reset validation on form
form.removeClass("form-error"); // remove error class from form
});
});
DEMO: http://jsfiddle.net/F2Re4/11/

Use .valid() to test the form. See the click function for valid()
validate = function(){
$("#myForm").valid();
};
resetForm = function(){
var form = $("#myForm").validate();
form.resetForm();
};
DEMO: http://jsfiddle.net/tive/U2XKx/
Additionally use reset() as seen on w3schools to clear the text value.

Related

JS - When my Function removes a child Element all child Elements disappear [duplicate]

I have a HTML form where I use several buttons. The problem is that no matter which button I click, the form will get submitted even if the button is not of type "submit". e.g. Buttons like :<button>Click to do something</button>, result in form submission.
It's quite painful to do an e.preventDefault() for each one of these buttons.
I use jQuery and jQuery UI and the website is in HTML5.
Is there a way to disable this automatic behavior?
Buttons like <button>Click to do something</button> are submit buttons.
Set type="button" to change that. type="submit" is the default (as specified by the HTML spec):
The missing value default and invalid value default are the Submit Button state.
You could just try using return false (return false overrides default behaviour on every DOM element) like that :
myform.onsubmit = function ()
{
// do what you want
return false
}
and then submit your form using myform.submit()
or alternatively :
mybutton.onclick = function ()
{
// do what you want
return false
}
Also, if you use type="button" your form will not be submitted.
<button>'s are in fact submit buttons, they have no other main functionality. You will have to set the type to button.
But if you bind your event handler like below, you target all buttons and do not have to do it manually for each button!
$('form button').on("click",function(e){
e.preventDefault();
});
if you want to add directly to input as attribute, use this
onclick="return false;"
<input id = "btnPlay" type="button" onclick="return false;" value="play" />
this will prevent form submit behaviour
Like mas-designs said, call preventDefault(). You can call it on the form itself. Here's a function that does this for all forms, vanilla JS.
function forms_ini(){
for(var form of document.getElementsByTagName('form')){
form.addEventListener('submit', function(ev){
ev.preventDefault()
})
}
}
another one:
if(this.checkValidity() == false) {
$(this).addClass('was-validated');
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
}

jQuery one function not working as expected

I have the following jsp:
...
<script type="text/javascript">
$(function() {
// prevent multiple submissions
$('#saveCallListBtn').one("click", function() {
$('#callListForm').submit();
});
});
...
</script>
...
<form:form id="callListForm" commandName="callList" action="${contextPath}/calllist/save" method="POST" htmlEscape="true">
...
<td colspan="2" style="text-align: center">
<input id="saveCallListBtn" type="submit" value="Save" class="button-med"/>
</td>
...
</form:form>
The behavior I am looking for is to only all the form to be submitted once no matter how many times the save button is clicked. Using the jQuery .one function, I can get the above code to correctly work. As the form will submit multiple times if I click more than once.
The following code will work fine:
$('#saveCallListBtn').on("click", function() {
$(this).prop("disabled", true);
$('#callListForm').submit();
});
But I am interested to know what I am doing wrong with the .one function.
Note the type here:
<input id="saveCallListBtn" type="submit" value="Save" class="button-med"/>
A submit button in a form will submit the form, no JavaScript required. So when your handler is automatically removed, on the next click the default handling (submitting the form) occurs, courtesy of the browser.
The only reason you're not seeing the form submitted twice on first click, I suspect, is that the act of submitting the form begins the process of tearing down the page to make room for the result of the submission.
FWIW, I would suggest that you not have a click handler on the button, but rather a submit handler on the form that, if all is well and it's going to allow submission to occur, disables the button and sets a flag to prevent future form submission, since forms can be submitted in multiple ways. (On some forms, pressing Enter in a text field will do it, for instance.)
E.g.:
$("#callListForm").on("submit", function(e) {
var $btn = $("#saveCallListBtn");
var valid = !$btn.prop("disabled");
if (valid) {
// ...do any other validity checks you may want, set `valid` to false
// if problems encountered...
}
if (valid) {
$btn.prop("disabled", true);
} else {
e.preventDefault();
}
});
The jQuery one function will execute the event handler only once. However, the default behaviour of the element clicked will execute indefinitely.
Change the type of the button to button, such that it has no default behaviour:
<input id="saveCallListBtn" type="button" value="Save" class="button-med"/>

Bootstrap error alert using jQuery

I'm trying to display error alert messages using bootstrap alerts. If a user submits the form with some fields empty, an error should be displayed. However when i click submit nothing is displayed.
JS
<script type="text/javascript">
$(document).ready(function () {
$('form[name="register"]').on("submit", function (e) {
var email = $(this).find('input[name="email"]');
if ($.trim(email.val()) === "") {
e.preventDefault();
$("#errorAlert").slideDown(400);
} else {
$("#errorAlert").slideUp(400, function () {
email.val("");
});
}
});
$(".alert").find(".close").on("click", function (e) {
e.stopPropagation();
e.preventDefault();
$(this).closest(".alert").slideUp(400);
});
});
</script>
HTML
<div class="alert hide" id="errorAlert">
<a class="close">×</a>
Oops!!. You may have left some fields empty. Please fill them out.
</div>
<form name="register" action="" method="post">
<input type="text" name="email" />
<input type="submit" class="btn" value="Submit" />
</form>
When i remove the "hide" class from the div above, the alert message comes up even before the form is submitted. If i then close the alert and submit the form, the alert isn't displayed. How do i get it working. Thanks in advance
on your $("#errorAlert").slideDown(400), add .removeClass('hide')
that would be $("#errorAlert").hide().slideDown(400).removeClass('hide').
I'm suspecting hide class has display:none!important. so we have to remove the class.
DEMO fiddle
Demo
jquery
$(document).ready(function () {
// Run this code only when the DOM (all elements) are ready
$('form[name="register"]').on("submit", function (e) {
// Find all <form>s with the name "register", and bind a "submit" event handler
// Find the <input /> element with the name "username"
var email = $(this).find('input[name="email"]');
if ($.trim(email.val()) === "") {
// If its value is empty
e.preventDefault(); // Stop the form from submitting
$("#errorAlert").slideDown(400); // Show the Alert
} else {
e.preventDefault(); // Not needed, just for demonstration
$("#errorAlert").slideUp(400, function () { // Hide the Alert (if visible)
alert("Would be submitting form"); // Not needed, just for demonstration
username.val(""); // Not needed, just for demonstration
});
}
});
$(".alert").find(".close").on("click", function (e) {
// Find all elements with the "alert" class, get all descendant elements with the class "close", and bind a "click" event handler
e.stopPropagation(); // Don't allow the click to bubble up the DOM
e.preventDefault(); // Don't let any default functionality occur (in case it's a link)
$(this).closest(".alert").slideUp(400); // Hide this specific Alert
});
});
The problem's pretty simple. .hide is not a good idea to use here because it contains display: none with !important following it, so even when you are trying to display the alert, this property overrides it.
You could create a simple css:
.hid{
display:none;
}
Add the hid as class to the alert box instead of hide.
DEMO
You could simply delete the hide class and add style="display:none;" to the $('#errorAlert') element. This way, the element will not appear on page load, and jQuery will manipulate the display property when using slide* functions. (it would never delete/add Bootstrap's hide class.)
See fiddle: http://jsfiddle.net/X2B9h/
UPDATED: http://jsfiddle.net/crw4K/
EDIT: Changing my answer because I haven't had my coffee yet.
Okay, so my changes to your code:
I removed the class 'hide' from the alert div, and added an inline style tag with 'display:none;'
Also, I removed the initial
$(".alert").find(".close")...
and changed it to just
$(".close").on("click"...
EDIT: I think I have found your problem. The .hide class in bootstrap is:
display:none !important;
which means it takes top priority over every other css for the element. Meaning that when you do slide down, the display:none !important is still taking priority.
You could either remove the class entirely, and add your own inline style tag (as I have in my answer) or you could remove the class with jquery.

Jquery validator valid status with ajax submit

I am trying to post a form using ajax after a form has been validated. However the .valid seems to be wrong.
Multiple action type is desired based on button.
This example is also not showing the errors messages correctly upon submit
$('#submit').click( function(){
alert(validator.valid());
});
$('#submit2').click( function(){
alert(validator.valid());
//do something else
});
status become true if i enter a required field (e.g name)
this is the fiddle
try this fiddle
http://jsfiddle.net/r2HUu/4/
It's working. I just checked form' validation by $("#myForm").valid()
Quote OP:
"I am trying to post a form using ajax after a form has been validated"
As per documentation, your ajax goes inside the submitHandler callback function.
submitHandler (default: native form submit) Type: Function()Callback
for handling the actual submit when the form is valid. Gets the form
as the only argument. Replaces the default submit. The right place to
submit a form via Ajax after it validated.
Using this callback, the click is captured automatically and the function is only fired on a valid form.
$(function () {
var validator = $("#myForm").validate({
// rules and options,
submitHandler: function(form) {
// your ajax goes here
alert("valid form");
return false;
}
});
});
DEMO: http://jsfiddle.net/fXDwd/
Quote OP:
"However the .valid seems to be wrong."
EDIT
As per OP's comments and updated jsFiddle:
If you want to have multiple submit buttons do different things on one form, construct click handlers for each button which you've already done. Now you must move those buttons to outside of the <form></form> container. Otherwise, the plugin will treat them both as normal submit buttons and interfere with your click handlers.
The other problem is your implementation of .valid(). Attach it to the form element, $("#myForm"), not the validator initialization object.
HTML:
<form id="myForm" action="">
...
</form>
<input type="button" id="submit" value="Submit form" />
<input type="button" id="submit2" value="Submit form2" />
jQuery:
$(function () {
var validator = $("#myForm").validate({
// rules and options
});
$('#submit').click(function () {
alert($("#myForm").valid());
//do something
});
$('#submit2').click(function () {
alert($("#myForm").valid());
//do something else
});
});
DEMO: http://jsfiddle.net/vfrGU/

Disable form auto submit on button click

I have a HTML form where I use several buttons. The problem is that no matter which button I click, the form will get submitted even if the button is not of type "submit". e.g. Buttons like :<button>Click to do something</button>, result in form submission.
It's quite painful to do an e.preventDefault() for each one of these buttons.
I use jQuery and jQuery UI and the website is in HTML5.
Is there a way to disable this automatic behavior?
Buttons like <button>Click to do something</button> are submit buttons.
Set type="button" to change that. type="submit" is the default (as specified by the HTML spec):
The missing value default and invalid value default are the Submit Button state.
You could just try using return false (return false overrides default behaviour on every DOM element) like that :
myform.onsubmit = function ()
{
// do what you want
return false
}
and then submit your form using myform.submit()
or alternatively :
mybutton.onclick = function ()
{
// do what you want
return false
}
Also, if you use type="button" your form will not be submitted.
<button>'s are in fact submit buttons, they have no other main functionality. You will have to set the type to button.
But if you bind your event handler like below, you target all buttons and do not have to do it manually for each button!
$('form button').on("click",function(e){
e.preventDefault();
});
if you want to add directly to input as attribute, use this
onclick="return false;"
<input id = "btnPlay" type="button" onclick="return false;" value="play" />
this will prevent form submit behaviour
Like mas-designs said, call preventDefault(). You can call it on the form itself. Here's a function that does this for all forms, vanilla JS.
function forms_ini(){
for(var form of document.getElementsByTagName('form')){
form.addEventListener('submit', function(ev){
ev.preventDefault()
})
}
}
another one:
if(this.checkValidity() == false) {
$(this).addClass('was-validated');
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
}

Categories