
September 2nd, 2005, 12:50 PM
|
|
Contributing User
|
|
Join Date: Apr 2007
Location: Maryland, USA
Posts: 402
Time spent in forums: 5 h 4 m 30 sec
Reputation Power: 2
|
|
|
building javascript objects
I'm trying to use js to loop through a set of fields and build an object from the field names and values. Can someone tell me why the code below isn't working? I've stuck in a lot of alerts for debugging purposes, and the alerts are returning the correct values, but the the values of all the properties are being returned as 'undefined'.
Code:
<html>
<head>
<script type='text/javascript'>
function buildObj(setNum)
{
var obj=new Object();
var fldList=new Array('name','job','gender');
for(var i=0; i<fldList.length; i++)
{
var k= fldList[i];
var fld=k+setNum
var val=document.getElementById(fld).value;
alert('Value of ' + fld +'='+val+'nSetting ' +k+'='+val);
obj[k]=val;
}
return obj;
}
function getStr(obj)
{
var str='Your Object:n';
for(var key in obj)
{
str+=key+":"+obj.key+"n";
}
return str
}
</script>
</head>
<body>
Name: <input type='text' id='name1' /><br />
Job: <input type='text' id='job1' /><br />
Gender: <input type='text' id='gender1' /><br />
<button id='btn' onclick='var n=buildObj(1); var s=getStr(n); alert(s);'>Go</button><br />
</body>
</html>
Thanks a ton.
|