I have a form with multiple input fields and a select field. I have an attribute of required for multiple fields. I have created a validation code snippet which should check all required fields and display a message when field is empty.
However the problem is that it works only when first input field is empty. I would appriciate a hint.
Code for the function:
function lisa_a() {
//validator
var req = $(":input[required]").val();
var reqfield = $(":input[required]");
if (req == ""){
$(".error").remove();
var reqtxt = "<span class='error'>Nõutud</span>";
reqfield.each(function(){
$(this).after(reqtxt);
});
$("div#status").html("Please fill...");
//validator
}else{
var data = $("form#lisa_a_vorm").serialize();
$.ajax({
url : "/var_dump.php", //for testing
method: "POST",
data : data,
success:function(data) {
$("div#status").html(data);
}
});
$("form#lisa_a_vorm :input").each(function(){
$(this).val('');
});
$(".error").remove();
}
}
EDIT:
Searched some more and discovered .filter looping through fields. Adjusted my code:
function lisa_a() {
//validator
var emptyfields = $(":input[required]").filter(function(){
return $.trim($(this).val()).length === 0;
}).length > 0;
$(".error").remove();
if (emptyfields){
$(":input[required]").after("<span class='error'>Nõutud</span>");
$("div#status").html("Palun täida kõik nõutud väljad!");
}else{
var data = $("form#lisa_a_vorm").serialize();
$.ajax({
url : "/wp-content/themes/origin/TCDB/php/var_dump.php",
method: "POST",
data : data,
success:function(data) {
$("div#status").html(data);
}
});
$("form#lisa_a_vorm :input").each(function(){
$(this).val('');
});
$(".error").remove();
}
}
It's not perfect as i don't quite understand .filter basics. Am i correct if i say that the filter function returns the number of trimmed required input fields that have the value 0, which means that they are empty. If the number of those fields is greater than 0, then it returns true, else it returns false. EDIT: i think i just got the point. The solution came from this answer.