【发布时间】:2016-04-17 15:25:43
【问题描述】:
我用 Jquery 编写了以下简单的验证代码,一切正常,但只显示最后一个字段的错误。 我已经开始放置这个带有错误 div 的字段集:
<fieldset data-check-id="1">
<div class="fs-error"></div>
<input type="text" size="50" id="ptitle" name="title" />
<input type="text" id="address" name="p_address">
</fieldset>
接下来我尝试了类似的方法
function check($fs){
var ok = true;
switch($fs.attr('data-check-id')){
case '1':
$ptitle = $('#ptitle',$fs);
$address = $('#address',$fs);
//title
if ($ptitle.val().length == 0) {
ok=false;
jQuery( "#ptitle" ).css( "border-bottom", "2px solid red" );
jQuery('.fs-error').html('<span style="color:red;"> Error 1 </span>');
jQuery('.fs-error').show();
}
else{
jQuery( "#ptitle" ).css( "border-bottom", "2px solid rgb(0, 102, 0)" );
jQuery('.fs-error').hide();
}
//Address
if ($address.val().length == 0) {
ok=false;
jQuery( "#address" ).css( "border-bottom", "2px solid red" );
jQuery('.fs-error').html('<span style="color:red;"> Error 2 </span>');
jQuery('.fs-error').show();
}
else{
jQuery( "#address" ).css( "border-bottom", "2px solid rgb(0, 102, 0)" );
jQuery('.fs-error').hide();
}
break;
}
if(ok === true){
$fs.attr('data-complete', true);
return true;
}
else{
$fs.attr('data-complete', false);
return false;
}
}
检查功能
function form_completeCheck(){
var ok = true;
$('fieldset').each(function(index,elem){
$this = $(this);
if ($this.attr('data-complete') != 'true') {
ok = false;
};
})
if (ok === true) {
//go go go..
return true;
}
else{
// stop
return false;
}
}
现在一切正常,但如果标题和地址均未填写,则仅显示地址错误(错误 2)。如果我插入地址,标题输入会以红色边框突出显示,但不会显示其消息(错误 1)。我做错了什么?提前致谢
【问题讨论】:
-
“它只显示地址错误(错误 2)” 似乎正在覆盖现有的
htmljQuery('.fs-error').html('<span style="color:red;"> Error 2 </span>');?您也可以使用html5、css来实现需求。
标签: javascript jquery forms validation