TheElbenreich
TheElbenreich

Reputation: 13

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.

Upvotes: 0

Views: 2389

Answers (6)

tzl
tzl

Reputation: 11

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("");
        }
    });
});

Upvotes: 0

Hemant Dubey
Hemant Dubey

Reputation: 143

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

Upvotes: 1

Deepu Sasidharan
Deepu Sasidharan

Reputation: 5309

Try this....

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

This works fine for me.

Upvotes: 0

Rafael Gomes Francisco
Rafael Gomes Francisco

Reputation: 2322

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("");
        }
   });
});

Upvotes: 0

Josh Beam
Josh Beam

Reputation: 19802

Use .prop() (see the jsfiddle):

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

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

Upvotes: 0

Ajey
Ajey

Reputation: 8212

$("#username").focus(function(){
    $(this).val("");
});

As simple as it can get.

Upvotes: 0

Related Questions