Below is my coding which is suppose to validate textareas which are empty or contains 5 characters or less.
function validation() {
var context = $('#optionAndAnswer');
var currenttotal = context.find('.answerBtnsOn').length;
alertValidation= "";
// Note, this is just so it's declared...
var textAreaO = $(".textAreaQuestion");
if (textAreaO.val() == ""){
alertValidation += "\nYou have not entered a valid Question\n";
} else if (textAreaO.val().length < 5){
alertValidation += "\nYou have not entered a valid Question\n";
}
if(alertValidation != "")
{
alert(alertValidation);
return false;
}
return true;
}
The problem is that lets say I have 2 textareas with the same class (.textAreaQuestion), then if one one of the two textareas is empty or less than 5 characters, then there is no validation (no alert appears) which is incorrect as it should appear. It only appears if both textareas are empty or less than 5 characters. So how can this code be manipulated so that if there is a textarea out of many textareas which is empty or less than 5 characters, then show the alert?
Thanks
The .val() method returns the value of the first matched element:
You should iterate through the matched elements to treat them separately. Something like this:
DEMO