getElementsByName undefined for dynamic elements (radio buttons)

D

Dr John Stockton

JRS: In article <[email protected]>, dated Fri,
5 May 2006 15:36:22 remote, seen in ASM
RobG a écrit :
RobG said on 05/05/2006 12:49 PM AEST:
[...]
var companys = document.getElementsByName("company");

var companies = ...

hu? var compagnies = ...
why to use absolutly correct english about variables ?

It's good to inform foreigners (including the chronologically retarded)
about correct spelling, if it is done economically.

OTOH, there is much to be said for using (on pages in English) variable
names which are not true English words (humor, for example), since then
when using text-searching tools an author can discriminate between the
concealed javascript form and the form shown to the page reader.
 
T

Thomas 'PointedEars' Lahn

Michael said:
// If dom set to false, use IE method to add element
if (!dom){
try {
oRadio = document.createElement('<input type="radio"'
+ ' name="' + grpName + '">');
form.appendChild(oRadio);
} catch (e){ e = true;}

[snip]

An alternative version that avoids exception handling could look
something like:

/* Takes three arguments and returns a boolean to indicate
* success (true) or failure (false).
*
* groupName - Name used for the new radio button group.
* quantity - Number of radio buttons to add.
* container - Reference to a block-level element, to
* which the new controls will be added.
*/
var addRadioButtons = function() {
function create(name) {
var element = document.createElement('input');

if (element) {
element.name = name;
element.type = 'radio';
}
return element;
}

/* If the host is IE, the function declaration below
* will override the one above.
*/
/*@cc_on @*/
/*@if (@_jscript)
function create(name) {
return document.createElement('<input type="radio" name="'
+ name + '">');
}
@end @*/
[...]

Here is a more general solution to this problem:

/**
* Creates an element of the type specified, using the
* <code>document.createElement()</code> method if supported.
* This method works with MSIE, too, for if JScript is used,
* it is tried to use the start tag as is instead of passing
* only the element type, and adding properties later.
*
* @author
* (C) 2004, 2006 Thomas Lahn &lt;[email protected]&gt;
* @partof
* http://pointedears.de/scripts/dhtml.js
* @param sTag : string
* Start tag or element type of the element to be created.
* Passing a start tag even works if the UA is not MSIE,
* as attributes and values given are parsed from left to
* right into the corresponding element object properties.
* @return type object
* A reference to a new <code>Element</code> object with the
* <code>nodeName</code> property set to <code>sTagName</code>,
* and the <code>localName</code>, <code>prefix</code>,
* and <code>namespaceURI</code> properties set to
* <code>null</code>.
* @see
* @link{dom2-core#ID-2141741547},
* @link{msdn#workshop/author/dhtml/reference/methods/createelement.asp}
* http://pointedears.de/scripts/JSdoc/
*/
function createElement(sTag)
{
var o = null;

if (sTag
&& typeof document != "undefined"
&& dhtml.isMethod(document.createElement))
{
/*@cc_on @*/
/*@if (@_jscript)
o = document.createElement(sTag);
@end @*/

if (!o)
{
var aTagComponents = sTag.replace(/^<?\s*|\s*>?$/g, "")
.replace(/\s+/, " ").replace(/ = /g, "=").split(" ");
o = document.createElement(aTagComponents[0]);
if (o)
{
aTagComponents.shift();
var attrs = aTagComponents.join(" ");
var m;
while ((m = /([^\s=]+)\s*(=\s*(\S+)\s*)?/g.exec(attrs)))
{
setAttr(o, m[1].toLowerCase(), m[3]);
}
}
}
}

return o;
}

/**
* Sets the value of an attribute of an HTMLElement object.
*
* @author
* (C) 2003, 2006 Thomas Lahn &lt;[email protected]&gt;
* @partof
* http://pointedears.de/scripts/dhtml.js
* @param sAttrName: string
* Name of the attribute for which the value should be set.
* Attribute names for which an ECMAScript language binding
* is defined in W3C DOM Level 2 HTML, are automatically
* mapped to the corresponding element object property.
* All attribute names are automatically mapped to their
* camelCased equivalent.
*
* Semicolon-separated style property declarations (in
* form of colon-separated name-value pairs each) of a
* <code>style</code> attribute value are mapped to the
* corresponding properties of the object referenced by
* the <code>style</code> property of the element object.
* Declarations are evaluated from left to right, where
* property values complement or replace the previously
* defined ones.
* @param attrValue
* Value of the attribute to be set. The value is
* converted to number if it can be interpreted as such.
* @returns
* The value of the attribute of the element object;
* a null-string if no matching object exists or if the DOM
* does not provide retrieval of the attribute's values.
*/
function setAttr(o, sAttrName, attrValue)
{
var result = "";

if (o && sAttrName)
{
var attrMap = {
alink: "aLink",
accesskey: "accessKey",
bgcolor: "bgColor",
cellpadding: "cellPadding",
cellspacing: "cellSpacing",
"char": "ch",
charoff: "chOff",
"class": "className",
codebase: "codeBase",
codetype: "codeType",
datetime: "dateTime",
frameborder: "frameBorder",
htmlfor: "htmlFor",
ismap: "isMap",
longdesc: "longDesc",
maxlength: "maxLength",
marginheight: "marginHeight",
marginwidth: "marginWidth",
nohref: "noHref",
noresize: "noResize",
noshade: "noShade",
nowrap: "noWrap",
readonly: "readOnly",
rowspan: "rowSpan",
tabindex: "tabIndex",
usemap: "useMap",
valuetype: "valueType",
vlink: "vLink"
};

// camel-case specific attribute names
if (typeof attrMap[sAttrName] != "undefined")
{
sAttrName = attrMap[sAttrName];
}

var
hyphenatedToCamelCase = function(s)
{
return s.replace(
/-([a-z])/g,
function(match, p1, offset, input)
{
return p1.toUpperCase();
})
},

strToValue = function(s)
{
s = s.replace(/^["']|["']$/g, "");
return isNaN(s) ? s : +s;
};

// camel-case hyphenated attribute names
sAttrName = hyphenatedToCamelCase(sAttrName);

if (typeof attrValue != "undefined")
{
attrValue = strToValue(attrValue);
if (sAttrName == "style" && typeof attrValue == "string")
{
var styleProps = attrValue.split(/\s*;\s*/);
for (var j = 0, len = styleProps.length; j < len; j++)
{
var
stylePair = styleProps[j].split(/\s*:\s*/),
stylePropName = stylePair[0].toLowerCase(),
stylePropVal = stylePair[1];

dhtml.setStyleProperty(o,
hyphenatedToCamelCase(stylePropName),
strToValue(stylePropVal));
}
}
else
{
result = o[sAttrName] = attrValue;
}
}
else if (!(o[sAttrName] = true))
{
result = o[sAttrName] = sAttrName;
}
}

return result;
}


PointedEars
 
T

Thomas 'PointedEars' Lahn

Michael said:
On 05/05/2006 15:02, VK wrote:
[setAttribute versus equivalent HTML short cut properties]
AFAIK they are dealing with completely different domains.

They are not.

True. The domains are not completely different. But they are
slightly different.

HTML shortcut properties are live with both writing and reading.
setAttribute() is "live" on write access; however, getAttribute()
is not "live" on read access: e.g. when the form control value is
changed as compared to the default, .value evaluates to a different
value than getAttribute("value"), and getAttribute("value") returns
the same value as .defaultValue evaluates to.
The defined short cut properties all have types. If the right-hand
operand is not of that type, it will be coerced upon assignment.

It is implicit type conversion through a setter.
For a highly visible example, create a text input element and assign an
object reference to its value property.

See above.


PointedEars
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,796
Messages
2,569,645
Members
45,371
Latest member
TroyHursey

Latest Threads

Top