Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - each loop on multiple element types

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);
            }
        }
    });
});
like image 261
Stan Avatar asked Dec 27 '22 06:12

Stan


2 Answers

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')
like image 159
Adam Hopkinson Avatar answered Jan 12 '23 07:01

Adam Hopkinson


You can use a comma to select multiple elements:

form.find("input,textarea").each(function(){...} );
like image 20
driangle Avatar answered Jan 12 '23 07:01

driangle