...

View Full Version : Problem with function accessing a form element



acomber
07-03-2011, 02:29 PM
Hello

I am fairly new to Javascript. I have a function which takes a string which consists of key value pairs and sets a form control based on key being the form element name and value being the value to set. eg string could be "key1=orange;key2=2;key3=whetever"

Here is the function:

function processresponse(frm, serverResponse) {
var items = serverResponse.split(";");
for(var i = 0; i < items.length; i++)
{
var item = items[i];
var eqchar = item.search("=");
if(eqchar != -1)
{
var key = item.slice(0, eqchar);
var value = item.slice(eqchar+1);
var elemname = key;

if(document.getElementById(elemname) != null) {
var type = frm.elements[elemname].type;
if (type=="checkbox") {
value == "1" ? frm.elements[elemname].checked=true : frm.elements[elemname].checked=false;
}
else if (type=="text"){
//do processing for text (text input)
frm.elements[elemname].value = value;
}
else if(type=="select-one"){
//only one is openformmode - default to [0] - true
if(value == "0" || value.length == 0)
{
frm.elements[elemname].options[0].selected = true;
}
else
{
frm.elements[elemname].options[1].selected = true;
}
}
else {
alert("unknown ctrl type: " + type + " name: " + frm.elements[elemname].name + " val: " + value + " key: " + key);
}
} //if(frm.getElementById(elemname)
}
}
}

The problem line is:
var type = frm.elements[elemname].type;

elemname is case sensitive so if for example the form element is called dog and the string elemname is Dog, then the line fails with Error: 'elements[...].type' is null or not an object

So my check if(document.getElementById(elemname) != null) is insufficient to guard against this.

I realise I could do a try catch but there must be a more legant way than that.

How can I test the formname more reliably?

Any ideas would be very welcome.

Angus

Logic Ali
07-03-2011, 05:19 PM
document.getElementById(elemname) is an incorrect test, because document.getElementById expects ( or should expect ) an ID as a parameter, not a name.

var type = frm.elements[elemname] ? frm.elements[elemname].type : "";

A more compact method is to make temporary use of the declared variable:

var elemType = ( elemType = frm.elements[elemname] ) ? elemType.type : "";

acomber
07-03-2011, 10:48 PM
Thanks for that. yes I see I was confused between id and name. Fixed, great :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum