外观:
应该是什么:
由于某种原因,每次我在输入框中键入内容时,都会添加另一个错误字形。有人能帮我吗?
HTML代码
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-12">
<div class="form-group has-feedback" id="num">
<input type="text" required pattern="[a-z]{1}[0-9]{7}" name="studo_number" id="studo_number" class="form-control input-lg" placeholder="Student/docent nummer" tabindex="4" title="Het student/docent nummer moet beginnen met een kleine letter gevolgd door 7 cijfers." maxlength="8">
</div>
</div>
</div>
jQuery代码
jQuery(function () {
$("#studo_number").keyup(function () {
var VAL = this.value;
var studo = new RegExp('[a-z]{1}[0-9]{7}');
if (studo.test(VAL)) {
if ($('#num').hasClass('has-error')){
$(this).parent().removeClass('has-error');
}
$('#num').addClass('has-success');
$(this).addClass('has-success');
$(this).after('<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>');
}
else{
$('#num').addClass('has-error');
$(this).addClass('has-error');
$(this).after('<span class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>');
}
});
});
您的问题是,无论何时keyup
,都会使用方法创建一个新元素.after()
。
像这样的事情可以解决您的问题,我们在执行之前尚未执行的操作之前先进行检查:
jQuery(function () {
$("#studo_number").keyup(function () {
var VAL = this.value;
var studo = new RegExp('[a-z]{1}[0-9]{7}');
//Check if input is good and we not already pass in this part
if (studo.test(VAL) && !$('#num').hasClass('has-success')) {
//Remove if exist the span glyphicon-remove and the class has-error
if ($('#num').hasClass('has-error')){
$(this).parent().find('.glyphicon-remove').remove();
$(this).parent().removeClass('has-error');
}
$('#num').addClass('has-success');
$(this).addClass('has-success');
$(this).after('<span class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>');
} else if (!studo.test(VAL) && !$('#num').hasClass('has-error')) {
//Remove if exist the span glyphicon-ok and the class has-success
if ($('#num').hasClass('has-success')){
$(this).parent().find('.glyphicon-ok').remove();
$(this).parent().removeClass('has-success');
}
$('#num').addClass('has-error');
$(this).addClass('has-error');
$(this).after('<span class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>');
}
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句