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

时间:2016-05-12 15:15:25

标签: javascript jquery html

<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为#username的按钮时将光标聚焦到textarea #messageBoxSignIn。但是,当用户在没有输入任何内容的情况下点击textarea #username之外时,我希望输入值返回“输入用户名”

我该怎么做?

4 个答案:

答案 0 :(得分:2)

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

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

您可以尝试here

答案 1 :(得分:1)

$('#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');
    }
});

答案 2 :(得分:1)

<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/

答案 3 :(得分:1)

你做错了。您需要将属性'placeholder'添加到input元素。你不需要所有这些javascript。浏览器将自行进行替换。

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