jQuery - 多个元素类型的每个循环

时间:2012-02-09 20:10:42

标签: javascript jquery

我构建了非常简单的验证器,当有人试图提交空表单时,它将显示我的自定义错误消息。但我有一些问题。

我在.each()元素上有:input循环 - 如何让它循环遍历:inputtextarea

我使用$(this).parent()来获取输入的表单对象,但是如何确保它是表单,而不是像div这样的其他元素?

带注释的代码

$('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);
            }
        }
    });
});

3 个答案:

答案 0 :(得分:6)

问题1:

我有.each()循环:输入元素 - 如何让它循环:input和textarea?

<强>答案:

$(':input, textarea').

问题2:

我使用$(this).parent()来获取输入的表单对象,但是如何确保它是表单,而不是像div这样的其他元素?

<强>答案:

$(this).closest('form')

答案 1 :(得分:2)

您可以使用逗号选择多个元素:

form.find("input,textarea").each(function(){...} );

答案 2 :(得分:0)

迭代输入和textarea:

$('.' + formClass + ' :input, .' + formClass + ' textarea').each...

访问父表单:

$(this).parents("form")