简体   繁体   中英

How to clear an input on focus the first time?

I have 2 inputs:

<input type="text" value="username">
<input type="password" value="password">

I want to delete the default value (just the first time) if i'm in a specific input. I have add attribute with JavaScript like this:

onfocus="this.value='';"

But this it clear the input every time focused on it. How to clear the input just the first time focus on it ?

What you want is called a placeholder : a default value that is automatically removed.

If you can accept your placeholder being not visible for IE9- users , do this :

<input type="text" placeholder="username">

If you need to be compatible with IE9, use one of the many polyfills , people have taken care of the implementation details for you.

Just use placeholder in input, for example

<input type="text" placeholder="username">

It's good to give name for every input, so:

<input type="text" name="username" placeholder="username">

尝试

onfocus="if(this.flag == undefined){ this.flag = true; this.value=''; }"

If you're using jQuery, you can use this:

<input type="text" name="username" value="username" />

Javascript:

$('input[name=username]').one('focus', function() {
    $(this).val('');
});

.one() Will only fire the bound event once

Try like this:-

$('.text').focus(function() {
    if (this.value == this.value) {
        $(this).val("");
    }
}).blur(function() {
    if (this.value == "") {
        $(this).val(this.value);
    }
});

http://jsfiddle.net/32Tns/296/

Just put a check on your onfocus function

    onfocus="if(this.value == 'username'){this.value='';}"


<input type="text" value="username" onfocus="if(this.value == 'username'){this.value='';}">
    <input type="password" value="password" onfocus="if(this.value == 'password'){this.value='';}">

JSFIDDLE EXAMPLE

<input type="text" value="username" id="username" title="username" />

$( '#username' ).bind({
    'focus': function( event ) {
       $( this ).val( '' );
    },
    'blur': function( event ) {
       var obj = $( this ),
           title = obj.attr( 'title' );
       obj.val( title );
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM