views:

48

answers:

1

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

A: 

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.

Nick Craver
Hi thanks for the quick response it still deletes whatever the user puts in the box and replaces it with "Full Name" it seems to be ignoring the bit saying if its blank
Jamie Taylor
@Jamie - Is your old handler still attached? Make sure there isn't another function still running...if you're using the function one and not my last version, the `.val()` will get the value of the *first* `.fullname` field, if you have more than one this will be a problem, is that the case?
Nick Craver
Hi here's a link to what i'm doing the full name field shouldn't delete what the user enters - http://www.hpb.co.uk/opendays/map/default3.aspx Thanks
Jamie Taylor
@Jamie - I added a solution for this...you're adding them dynamically, and adding lots of them, that's the multiple problem I was talking about. Just remove the `onFocus="doFocusNew();" onBlur="doBlurNew();"` from the markup and use the `.live()` answer I have above. Also make sure to update your jQuery to 1.4.2 so `.live()` works with the `focus` and `blur` events (otherwise you'll need to use `focusin` and `focusout`).
Nick Craver
Thank you it's brilliant
Jamie Taylor