使用 jQuery,当我在输入框外部单击时,如何更改输入元素的值

Using jQuery, how do I change the input element's value when I click outside of the input box?

本文关键字:输入 何更改 元素 单击 jQuery 使用 外部      更新时间:2023-09-26
<input type="text" size="13px" name="username" id="username" value="enter username" onclick='document.signIn.username.value = ""' />
$(function() {
    $('#messageBoxSignIn').click(function() {
        $('#username').val('');
        $('#username').focus();
    });
});

我目前有 jQuery 代码,使输入值为零,并在单击带有 ID #messageBoxSignIn的按钮时将光标聚焦到文本区域#username。但是,当用户在文本区域外单击#username而不输入任何内容时,我希望输入值返回到"输入用户名"。

我该怎么做?

如果HTML5适合你,你可以为此使用placeholder属性。你不需要jQuery。

<input type="text" placeholder="Enter Username">

你可以在这里尝试。

$('#username').blur(function(){
    if ($(this).val().length == 0) {
        $(this).val('Enter Username');
    }
});

$('#username').on('blur', function() {
    if ($(this).val().length == 0) {
        $(this).val('Enter Username');
    }
});
<input type="text" name="search" value="enter username" onblur="if(this.value == '') { this.value='enter username'}" onfocus="if (this.value == 'enter username') {this.value=''}">

https://jsfiddle.net/IA7medd/ur9ctku2/

你做错了。 您需要将属性"占位符"添加到输入元素。 你不需要所有这些JavaScript。 浏览器将自行进行替换。

http://www.w3schools.com/tags/att_input_placeholder.asp