78
rated 0 times
[
85]
[
7]
/ answers: 1 / hits: 16332
/ 13 Years ago, thu, february 9, 2012, 12:00:00
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);
}
}
});
});
More From » jquery