P
Peter Laman
In my app I need to dynamically generate a series hyperlinks. Each
hyperlink's action must be to focus a field in a <form>. I created the
following function to create such a link (the argument is a field
object, e.g. <input>):
function createFieldAnchor(field, linkText)
{
var anchor = document.createElement("a");
anchor.field = field;
anchor.href='javascript:this.focusField()';
anchor.innerHTML = linkText;
anchor.focusField = function()
{
var f = this.field;
f.focus();
f.select();
}
return anchor;
}
The link does not work. Debugging shows that the problem is in
'javascript:this.focusField()'. The 'this' operator does not refer to
the anchor here (as I expected), but to the window object!
Is there a simple way to get a reference to the anchor in that
context?
I thought up the following 'tricky' solution, which works, but it's
not a very elegant solution:
//General function to implement auto-increments on an object.
function genAutoInc(obj)
{
if (obj.autoIncSeed == null) {
obj.autoIncSeed = 0;
}
obj.autoIncSeed++;
return obj.autoIncSeed;
}
//This version assigns a unique ID to the anchor and uses that to
refer to it in the HREF.
function createFieldAnchor2(field, linkText)
{
var anchor = document.createElement("a");
anchor.field = field;
anchor.id = 'dynamicId'+genAutoInc(field.ownerDocument);
anchor.href='javascript:document.getElementById("'+anchor.id
+'").focusField()';
anchor.innerHTML = linkText;
anchor.focusField = function()
{
var f = this.field;
f.focus();
f.select();
}
return anchor;
}
hyperlink's action must be to focus a field in a <form>. I created the
following function to create such a link (the argument is a field
object, e.g. <input>):
function createFieldAnchor(field, linkText)
{
var anchor = document.createElement("a");
anchor.field = field;
anchor.href='javascript:this.focusField()';
anchor.innerHTML = linkText;
anchor.focusField = function()
{
var f = this.field;
f.focus();
f.select();
}
return anchor;
}
The link does not work. Debugging shows that the problem is in
'javascript:this.focusField()'. The 'this' operator does not refer to
the anchor here (as I expected), but to the window object!
Is there a simple way to get a reference to the anchor in that
context?
I thought up the following 'tricky' solution, which works, but it's
not a very elegant solution:
//General function to implement auto-increments on an object.
function genAutoInc(obj)
{
if (obj.autoIncSeed == null) {
obj.autoIncSeed = 0;
}
obj.autoIncSeed++;
return obj.autoIncSeed;
}
//This version assigns a unique ID to the anchor and uses that to
refer to it in the HREF.
function createFieldAnchor2(field, linkText)
{
var anchor = document.createElement("a");
anchor.field = field;
anchor.id = 'dynamicId'+genAutoInc(field.ownerDocument);
anchor.href='javascript:document.getElementById("'+anchor.id
+'").focusField()';
anchor.innerHTML = linkText;
anchor.focusField = function()
{
var f = this.field;
f.focus();
f.select();
}
return anchor;
}