Question

Hi I'm trying to get my onblur and onfocus functions to work but they don't seem to be doing the right thing - i'm trying to say if the field "fullname" is empty then place "Full Name" in the field and if someone has entered something leave it as it is. At the moment it clears the field if it says "Full Name" and if its empty it puts "Full Name" in. But my problem is that whenever anyone types anything in it keeps putting "Full Name" in the field.

Here's the code i'm using

function doFocusNew() { if ($('.fullname').val() != null && $('.address').val() != null) { $('.fullname').val('') } };

function doBlurNew() { if ($('.fullname').val() != null && $('.address').val() != null) { $('.fullname').val('Full Name') } };

Cheers Jamie

Was it helpful?

Solution

The values from .val() will never be null, they'll be empty strings, so you need a bit of adjustment. I think this is what you're after:

function doFocusNew() { 
  if ($('.fullname').val() == 'Full Name') {
    $('.fullname').val(''); //focused, "Full Name" was there, clear it
  } 
}
function doBlurNew() { 
  if ($('.fullname').val() == '') { 
    $('.fullname').val('Full Name'); //blurred, nothing there, put "Full Name" in
  } 
}

If they're textboxes, here's the complete/compact version:

$(function() {
  $('.fullname').focus(function() {
    if(this.value === 'Full Name') this.value = '';
  }).blur(function() {
    if(this.value === '') this.value = 'Full Name';
  });
});

Update: since you're adding them dynamically:

$(function() {
  $('.fullname').live('focus', function() {
    if(this.value === 'Full Name') this.value = '';
  }).live('blur', function() {
    if(this.value === '') this.value = 'Full Name';
  });
});

Be sure to have all the bug fixes, e.g. on the latest jQuery 1.4.2 release for this to work, I see you're on 1.4.0 right now.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top