This is my simple jQuery form validation/submit logic and it is working perfectly fine. But still I am posting this to see if someone check the logic and suggest me if there is any other simple way to get the same results.
In my form I put all input boxes and select into .valid1
class, all checkbox and radio buttons to .valid2
class. I am just wondering is there any way we can do this by putting all input sources under a single class.
$(document).ready(function(){
$("#sbutton").click(function(){
var submitflag = false;
var validflag = true;
validform();
// alert(submitflag);
if (submitflag){
$("form").submit();
}
function validform(){
$(".valid1").each(function(){
if ($(this).find("input").val() === ''){
// alert("I am input");
$(this).find(".error1").html($(this).find("label").html() +" " + "is required");
validflag = false;
}else{
$(this).find(".error1").html("");
}
if ($(this).find("select").val() === ''){
// alert("I am select");
$(this).find(".error2").html($(this).find("label").html() +" " + "is required");
validflag = false;
}else{
$(this).find(".error2").html("");
}
});
$(".valid2").each(function(){
if (!$(this).find("input:checked").val()){
// alert("I am cbox");
$(this).find(".error3").html($(this).find("label").html() +" " + "is required");
$(this).find(".error4").html("Agree terms and conditions");
validflag = false;
}else{
$(this).find(".error3, .error4").html("");
}
});
if(validflag){submitflag = true;}
}
});
});
div
s in one style, so that each errordiv
has the one class. \$\endgroup\$