2012-02-09 3 views
3

빈 양식을 제출하려고 할 때 사용자 정의 오류 메시지가 표시되는 간단한 간단한 유효성 검사기를 작성했습니다. 하지만 몇 가지 질문이 있습니다.jQuery - 여러 요소 유형의 각 루프

나는 :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); 
      } 
     } 
    }); 
}); 

답변

5

질문 1

코드 :

I가 .each()에 루프 : 입력 요소 - 어떻게 그것을 만들 수 있습니다 루프를 : 입력 및 텍스트 영역?

답변 :

$(':input, textarea'). 

질문 2 :

I는 입력의 양식 객체를 얻기 위해 (이) .parent() $를 사용하지만, 어떻게 그것을 확인 할 수 있습니다 양식, div와 같은 다른 요소가 아닌가?

답변 : 여러 요소를 선택하려면 쉼표를 사용할 수 있습니다

$(this).closest('form') 
+0

감사합니다. – sed

+0

그렇게하면 지글 거리고 불필요한 DOM 통과가 필요합니다. – AlienWebguy

+0

@AlienWebguy sizzle? 다중 선택자를 위해? 나는 정말로 지글 거리지 않는다. 그러나 나는 out-of-the-box jquery로 양쪽 다했다. –

2

:

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

하는 부모에 액세스하려면 :

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

입력 및 텍스트 영역 모두를 반복하려면 양식 :

$(this).parents("form")