Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
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

 Answers
35

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')

[#87564] Wednesday, February 8, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
victorr

Total Points: 193
Total Questions: 86
Total Answers: 105

Location: Pitcairn Islands
Member since Thu, Jun 24, 2021
3 Years ago
victorr questions
Fri, Nov 13, 20, 00:00, 4 Years ago
Sat, Jul 25, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;