1

I'm trying to add a generic simple function that shows/hides form field's associated hint texts when the field gets/loses focus:

        function capFirstLetter(string) {
           return string.charAt(0).toUpperCase() + string.slice(1);
        }

        function pairFieldHint(fieldName) {
           hintField = $('#hint' + capFirstLetter(fieldName));
           fieldName = $('#' + fieldName);
           hintField.toggle();
           fieldName.focus(function () {
              hintField.show('fast');
           });
           fieldName.blur(function() {
              hintField.hide('fast');
           });
        }

        pairFieldHint('companyname');
        pairFieldHint('address');

I thought I can write it once and use it for any similar field/hint pair based on the specific naming convention:

<label class="required">Company Name</label><input type="text" name="companyname" id="companyname" />
<div class="field-hint" id="hintCompanyname">Invoice to this name</div>

<label class="required">Address</label><input type="text" name="address"  id="address" />
<div class="field-hint" id="hintAddress">Eg. New York, 6th ave 4.</div>

The problem is that even if I click the companyname field, the address hint gets shown/hidden. It seems that the last pairFieldHint call overrides any prior ones.

See in action: http://jsfiddle.net/Kh62D/

Maybe the anonymus functions inside gets always overwritten? What should be wrong with it?

Attila Fulop
  • 6,861
  • 2
  • 44
  • 50

1 Answers1

3

You need to use var in your function to set local scoped variables (see http://jsfiddle.net/Kh62D/2/):

function pairFieldHint(fieldName) {
    var hintField = $('#hint' + capFirstLetter(fieldName));
    var fieldName = $('#' + fieldName);
    /* ...the rest of your code as before... */
}

When you omit var, it's actually creating a property on the window object. So hintField = ... is equivalent to window.hintField = ... when you omit var. This is virtually the same as setting a global variable.

So the way you had it, every time pairFieldHint got called, it would override the values of hintField and fieldname, meaning that these values would in the end all be whatever the last time you called it set them to (in your case, that was the values associated with "address").

By making them local variables with var, they are appropriately scoped and visible only within the function, so calling the block again does not overwrite the variables from when you called the function earlier.

Community
  • 1
  • 1
Ben Lee
  • 52,489
  • 13
  • 125
  • 145
  • Thank you Ben, for the detailed explanation. I wasn't aware of the window property thing AND I think I spent too much time in php :) – Attila Fulop Mar 13 '12 at 14:41