例如,我有默认值为5的输入,但是用户使用backspace删除它,所以之后我想再次设置默认值。
发布于 2016-05-17 11:09:57
假设您的输入有一个id test,如下所示
$('#test').on('change blur',function(){
if($(this).val().trim().length === 0){
$(this).val(5);
}
})<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="test" type="text" value = "5" />
发布于 2016-05-17 11:14:54
如果最初设置为defaultValue,则使用获取默认值:
$(':text').on('blur', function(e){
this.value = this.value.trim() || this.defaultValue;
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' value='5'>
发布于 2016-05-17 11:15:56
我建议不要使用keyup,因为这将阻止用户删除默认值,然后用新值进行更新(因为在keyup被backspace键触发后,就不会有值)。
相反,我建议使用change和blur来提供(假设相关元素保存在selector变量中):
$(selector).on('change blur', function() {
// sets the value of the element based on the current-value;
// if the value is equal to an empty string ('') once the
// leading and trailing white-space is removed (using
// String.prototype.trim()) then we set the value to the
// defaultValue (the value held by the <input> on page-load)
// otherwise we set it to the current-value:
this.value = this.value.trim() === '' ? this.defaultValue : this.value;
});如果您希望在普通JavaScript中实现相同的功能--同样假设相关元素保存在selector变量中--您可以使用以下方法:
function defaultIfEmpty(){
let el = this;
el.value = el.value.trim() === '' ? el.defaultValue : el.value;
}
selector.addEventListener('change', defaultIfEmpty);https://stackoverflow.com/questions/37274384
复制相似问题