我构建了非常简单的验证器,当有人试图提交空表单时,它将显示我的自定义错误消息.但我有一些问题.
我有.each()环路: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);
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
问题1:
我有.each()循环:输入元素 - 如何让它循环:输入和textarea?
回答:
$(':input, textarea').
Run Code Online (Sandbox Code Playgroud)
问题2:
我使用$(本).parent()来获取输入的表单对象,但我怎么能保证它是形式,而不是像DIV一些其他的元素?
回答:
$(this).closest('form')
Run Code Online (Sandbox Code Playgroud)