简体   繁体   中英

jQuery focus() and empty field

I want to empty a login field when it is selected. I'm working with a JS/jQuery-Book and copied the example exactly like this into my document but it doesnt want to work...

Field:

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

jQuery:

$(document).ready(function(){
$("#username").focus(function(){
    var field = $(this);
    if(field.val() == field.attr("defaultValue")){
    field.val(""); // also tried field.val() = "";
    }
});
});

I already put an alert() after each line and I figured out that it doesnt go into the if-statement.

You can try this...

$("#username").focus(function(){
var field = $(this);
var username=field.attr("value");
if(field.val() == username){
    field.val(""); 
}
});

It is tested and work properly with your attr also....

Use jQuery method prop to get the DOM attribute instead of attr .

$(document).ready(function(){
    $("#username").focus(function(){
        var field = $(this);
        if(field.val() == field.prop("defaultValue")){   // or: field.val() == field[0].defaultValue
            field.val("");
        }
    });
});
$("#username").focus(function(){
    $(this).val("");
});

As simple as it can get.

Use .prop() (see the jsfiddle ):

$("#username").focus(function(){
    var field = $(this);

    if(field.val() == field.prop("defaultValue")) {
        field.val("");
    }
});

Try it:

<input type="text" id="username" value="Username" name="username" defaultValue="" />

And try it:

$(document).ready(function(){
    $("#username").focus(function(){
        if($(this).val() === $(this).attr("defaultValue")){
            $(this).val("");
        }
   });
});

Try this....

$(document).ready(function(){
var user = $("#username").val();
$("#username").focus(function()
{
if($(this).val()==user)
$(this).val("");
});
});

This works fine for me.

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