I am basically trying to do a form validation. Evertyhing works fine. Except one thing. First, here is my code:
$('#submit_btn').click(function(){
$("input:not([type=radio],[type=checkbox])").each(function() {
if ($(this).val() == ""){
$('#'+$(this).attr("name")+'_error').show("");
}
else{
$('#'+$(this).attr("name")+'_error').hide("normal");
}
});
if(!($("div[id$=error]").is(":visible")))
alert("a");
});
After clicking a submit button, it checks inputs that are not radio button or checkbox. And if the input is empty it shows an error.
If some input is typed, error becomes hidden.
At the end i check if any error message is visible, if not i will submit the form.
My problem is, i hide the error message with a little animation with .hide("normal"). So i believe while in the process of hiding the last error message, my last if statement executes and it thinks there is an visible error message (however, it was in the process of hide)
How can i execute my if statement after hide process is complete?
In my case, when there is no error message left, I get开发者_StackOverflow中文版 the alert after another click to submit button.
I wish i am clear about my issue. If not i will try to rewrite it.
Thanks!
Doing this with :visible
is a bit hacky, and definitely slow. Use a variable instead:
$('#submit_btn').click(function(){
var error = false;
$("input:not([type=radio],[type=checkbox])").each(function() {
if ($(this).val() == ""){
$('#'+$(this).attr("name")+'_error').show(400);
error = true;
}
else{
$('#'+$(this).attr("name")+'_error').hide(400);
}
});
if(error)
alert("a");
});
If your goal is to show the alert message after the .hide("normal")
function is finished animating then you need to pass a "callback" function as an argument to the .hide()
function. See the documentation.
See an example here:
$('#submit_btn').click(function(){
$("input:not([type=radio],[type=checkbox])").each(function() {
if ($(this).val() == ""){
$('#'+$(this).attr("name")+'_error').show("");
}
else{
$('#'+$(this).attr("name")+'_error').hide("normal", function() {
// This function will be executed when the "normal" animation is complete
if(!($("div[id$=error]").is(":visible")))
alert("a");
});
}
});
});
My 2 Cents... I will say though, that you might want to listen to everyone's encouragement to seek an elegant form validation plugin.
精彩评论