Reputation: 13
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
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
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
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
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
Reputation: 19802
Use .prop() (see the jsfiddle):
$("#username").focus(function(){
var field = $(this);
if(field.val() == field.prop("defaultValue")) {
field.val("");
}
});
Upvotes: 0
Reputation: 8212
$("#username").focus(function(){
$(this).val("");
});
As simple as it can get.
Upvotes: 0