빈 양식을 제출하려고 할 때 사용자 정의 오류 메시지가 표시되는 간단한 간단한 유효성 검사기를 작성했습니다. 하지만 몇 가지 질문이 있습니다.jQuery - 여러 요소 유형의 각 루프
나는 :input
요소에 루프가 있습니다. :input
과 textarea
을 통해 어떻게 루프를 만들 수 있습니까?
입력 양식 객체를 가져 오는 데 $(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);
}
}
});
});
감사합니다. – sed
그렇게하면 지글 거리고 불필요한 DOM 통과가 필요합니다. – AlienWebguy
@AlienWebguy sizzle? 다중 선택자를 위해? 나는 정말로 지글 거리지 않는다. 그러나 나는 out-of-the-box jquery로 양쪽 다했다. –