I am writing a basic jQuery form validation script and I have something like this going on:
(Please note, I have simplified the validation criteria since it is not the problem here.)
$('#contact-form').submit( function (event) {
event.preventDefault();
var name = $(this).find('input[type="text"]').val();
var message = $(this).find('textarea').val();
// Validation
if (name.length <= 3 || message.length <= 3) {
$(this).after('<span>Error<span>');
}
});
What I wnat to do is somhow make jQuery recognize the corect this where the error has ocured from the
if (name.length <= 3 || message.length <= 3) {
$(this).after('<span class="error">Error<span>');
}
statement and insert the error span after it. What I currently have inserts the error message only after the first input, not the input that had a mistake.
I know how to do it if I separate each element validation in its own if statement, but I think that would be unnecessary repetition.
Also please don’t suggest any validation plugins, I am aware of those, but I want to learn to do this on my own.
Thank you.
This in jquery refers to the element that generated the event: in your case
$(this)refers to the element with id = ‘contact.form’.You could do something like this: