I have 4 textboxes on my page. I used jquery focus and blur functions to make the default of the textbox to appear and disappear. My code:
$(document).ready(function() {
$("#name").focus(function() {
$("#name").removeClass("idleField").addClass("focusField");
if($("#name").val() == "username") {
$("#name").val('');
}
});
$("#name").blur(function() {
$("#name").removeClass("focusField").addClass("idleField");
if($("#name").val().length == 0) {
$("#name").val('username');
}
});
$("#password").focus(function() {
$("#name").removeClass("idleField").addClass("focusField");
if($("#password").val() == "password") {
$("#password").val('');
}
});
$("#password").blur(function() {
$("#name").removeClass("focusField").addClass("idleField");
if($("#password").val().length == 0) {
$("#password").val('password');
}
});
$("#firstname").focus(function() {
$("#firstname").removeClass("idleField").addClass("focusField");
if($("#firstname").val() == "firstname") {
$("#firstname").val('');
}
});
$("#firstname").blur(function() {
$("#firstname").removeClass("focusField").addClass("idleField");
if($("#firstname").val().length == 0) {
$("#firstname").val('firstname');
}
});
$("#lastname").focus(function() {
$("#lastname").removeClass("idleField").addClass("focusField");
if($("#lastname").val() == "lastname") {
$("#lastname").val('');
}
});
$("#lastname").blur(function() {
$("#lastname").removeClass("focusField").addClass("idleField");
if($("#lastname").val().length == 0) {
$("#lastname").val('lastname');
}
});
$("#email").focus(function() {
$("#email").removeClass("idleField").addClass("focusField");
if($("#email").val() == "username@example.com") {
$("#email").val('');
}
});
$("#email").blur(function() {
$("#email").removeClass("focusField").addClass("idleField");
if($("#email").val().length == 0) {
$("#email").val('username@example.com');
}
});
});
am i doing any thing wrong here?
Any help would be apreciated!
There is a mistake in your
#passwordfield, where you still have#nameas the selector.Also, it would be better to handle this differently, I would for example, store the original values as data attributes of each element that requires one, and then attach an event handler to all of them, which checks the element’s data attribute against it’s current value…
Assuming HTML something like this…
jQuery something like this works…