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?
You need to use var in your function to set local scoped variables (see http://jsfiddle.net/Kh62D/2/):
When you omit
var, it’s actually creating a property on thewindowobject. SohintField = ...is equivalent towindow.hintField = ...when you omitvar. This is virtually the same as setting a global variable.So the way you had it, every time
pairFieldHintgot called, it would override the values ofhintFieldandfieldname, 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.