I've build pretty simple validator that will display my custom error message when someone tries to submit empty form. But I have some questions.
I have .each()
loop on :input
elements - how can I make it loop through :input
and textarea
?
I use $(this).parent()
to get the form object of input, but how can I make sure that it is form, not some other element like div?
Code with comments
$('form input[type=submit]').click(function(){
// First we get the form class
var form = $(this).parent(); // How can I make sure that the form is selected, not some other parent like div?
var formClass = $(form).attr('class');
// Then remove every previous messages on this form
$('.' + formClass + ' .validation-error').each(function(){
$(this).remove();
});
// Iterate through every input to find data that needs to be validated
$('.' + formClass + ' :input').each(function(){ // How can I make this work with textareas as well as inputs without copying this whole each loop?
// If it is marked as required proceed
if ($(this).attr('required') == 'required'){
// Getting current text and placeholder text
var currentText = $(this).val();
var placeholderText = $(this).attr('placeholder');
// Replacing spaces to avoid empty requests
currentText = currentText.replace(' ', '');
placeholderText = placeholderText.replace(' ', '');
// If current text is empty or same as placeholder proceed
if (currentText == '' || currentText == placeholderText){
// Get input position in order to place error message
var inputPos = $(this).position();
var left = inputPos.left + 200;
var top = inputPos.top - 4;
// Generate error message container and error message itself
var errorMsg = '<div class="validation-error" style="position:absolute;left:' + left + 'px;top:' + top + 'px;"><- This</div>';
// Appending error message to parent - form
$(this).parent().append(errorMsg);
}
}
});
});
Question 1:
I have .each() loop on :input elements - how can I make it loop through :input and textarea?
Answer:
$(':input, textarea').
Question 2:
I use $(this).parent() to get the form object of input, but how can I make sure that it is form, not some other element like div?
Answer:
$(this).closest('form')
You can use a comma to select multiple elements:
form.find("input,textarea").each(function(){...} );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With