【发布时间】:2016-03-26 06:40:05
【问题描述】:
当焦点放在文本框上且文本框为空时,我在文本框附近显示“此字段是必需的”。当已经在该文本框中输入了某些内容时,我不想显示该错误消息。我通过这段代码实现了这一点。不过,对我来说,这里的问题是当文本框为空并且我继续输入退格键或任何其他非字符键时,“此字段是必需的”跨度元素不断堆积,这不好。我该如何解决?
html
<input data-required="true" type="text" name="foo" />
<select data-required="true" >
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
jquery
$("input[data-required='true'],select[data-required='true']").focus(function() {
$(this).after('<span class="label_error">This field is required</span>');
}).blur(function() {
$(this).next('span').remove();
}).change(function() {
if ($(this).val().length > 0) {
$(this).next('span').remove();
} else {
$(this).after('<span class="label_error">This field is required</span>');
}
}).keyup(function() {
if ($(this).val().length > 0) {
$(this).next('span').remove();
} else {
$(this).after('<span class="label_error">This field is required</span>');
}
});
【问题讨论】: