我有一个分配有默认值文本的输入框。当用户关注该字段时如何删除此文本::
代码
<input type="text" name="kp1_description" value="Enter Keypress Description">
$(document).ready(function(){
var Input = $('input[name=kp1_description]');
var default_value = Input.val();
Input.focus(function() {
if(Input.val() == default_value) Input.val("");
}).blur(function(){
if(Input.val().length == 0) Input.val(default_value);
});
})
那应该这样做。
更新,忘记焦点没有焦点事件的第二个参数,因为没有,它必须与模糊链接:
您还应该考虑为此创建自己的函数,例如:
$.fn.ToggleInputValue = function(){
return $(this).each(function(){
var Input = $(this);
var default_value = Input.val();
Input.focus(function() {
if(Input.val() == default_value) Input.val("");
}).blur(function(){
if(Input.val().length == 0) Input.val(default_value);
});
});
}
然后像这样使用
$(document).ready(function(){
$('input').ToggleInputValue();
})
Don't do it this way. Use a jQuery watermark script: http://code.google.com/p/jquery-watermark/
$("input[name='kp1_description']").watermark("Enter Keypress Description")
;
There are a lot of things you have to account for if you do it manually. For instance, what happens when the text box loses focus? If there's no value, you'd want to readd your helper text. If there is, you'd want to honor those changes.
Just easier to let other people do the heavy lifting :)
使用 HTML5,您可以在没有 Javascript 的情况下做到这一点:只需使用placeholder
而不是value
. 我认为这是一个很好的补充,但当然你需要先检查浏览器的兼容性。
<input type="text" id="anything" placeholder="enter keypress description">
i think this will help
$('input, textarea').each(function () {
var Input = $(this);
var default_value = Input.val();
Input.focus(function() {
if(Input.val() == default_value) Input.val("");
}).blur(function(){
if(Input.val().length == 0) Input.val(default_value);
});
});
var defaultForInput = "abc";
<input id="myTextInput" type="text" placeholder=defaultForInput />
提交表单时,检查 input(id="myTextInput") 值是否为“空字符串”,如果是,则将其替换为 (defaultForInput)。
Super Duper 短版
$('#input_id').focus(function() {
$(this).val("");
});
HTML:
<form method="post">
<input type="text" id="customer" value="Username"/>
<input type="Submit" value="Login" class="rc" />
</form>
Javascript代码:
<script>
$('#customer').on({
focus:function(){
if(this.value == 'Username') this.value = '';
},
blur:function(){
if(this.value == '') this.value = 'Username';
}
})
</script>
就是这样,我希望它会有所帮助。
纯 JavaScript:
(function () {
let input = document.querySelector ("input[name='kp1_description']");
input.onfocus = function () {
this.placeholder = this.value;
this.value = '';
};
})();
这会将值保留在占位符中,而不是完全删除它。如果您不喜欢这样,请删除占位符行。