Reputation: 12438
I am trying to dynamically create an object in javascript. Here is the JS code that I have written:
var table = $("#eidtPersonalInfoTbl");
var trs = table.find('tr');
var obj = { };
$(trs).each(function(index, row){
var field = $(row).find('td').eq(0).html();
var value = $(row).find('td').eq(1).html();
eval('obj.' + field + ' = ' + value );
});
And here is the HTML markup for the table:
<table class="table" border="1" id="eidtPersonalInfoTbl">
<tr>
<td class="span3 hidden-phone" > Name </td>
<td class="span5"> Name </td>
</tr>
<tr>
<td class="span3 hidden-phone"> Address</td>
<td class="span5"> Address </td>
</tr>
<tr>
<td class="span3 hidden-phone">Area</td>
<td class="span5"> Area</td>
<tr>
<tr>
<td class="span3 hidden-phone">Gender</td>
<td>Male</td> </tr>
<tr>
<td class="span3 hidden-phone" > Salutation </td>
<td class="span5"> Dr</td>
</tr>
<tr>
<td class="span3 hidden-phone">State</td>
<td class="span5"> State </td>
<tr>
<tr>
<td class="span3 hidden-phone">City</td>
<td class="span5"> City </td>
</tr>
<tr>
<td class="span3 hidden-phone" > Postel Code </td>
<td class="span5"> Postel Code </td>
</tr>
<tr>
<td class="span3 hidden-phone" > Phone# </td>
<td class="span5"> 04128741 </td>
</tr>
<tr>
<td class="span3 hidden-phone" > Mobile# </td>
<td class="span5"> 03218741525</td>
</tr>
<tr>
<td class="span3 hidden-phone" > Cover Letter </td>
<td>Cover letter goes here</td>
</tr>
<tr>
<td> <input type="submit" name="per-det" class="btn btn-success span5" value="Update and Cont."></td>
</tr>
Whenever I try to execute this, it gives me this error
Undefined variable Name
Upvotes: 1
Views: 2410
Reputation: 106385
It's far easier, safer and faster to use this:
obj[field] = value;
... instead of eval('obj.' + field + ' = "' + value + '"')
, which obviously has the same purpose.
You see what you see now because value
should be wrapped in the quotation marks. For example, if both field
and value
are equal to 'Name'
(string), the evalled expression as it stands now will look like...
obj.Name = Name
... obviously causing the 'Undefined variable Name' error.
Two sidenotes here. First, there's no sense wrapping trs
in jQuery object again in this line...
$(trs).each(function(index, row)
... as it already IS a jQuery object (result of table.find('tr')
). This redundancy is easier to see if you follow a simple convention: preceding names of all the variables that are used to store jQuery objects with $
:
var $table = $("#eidtPersonalInfoTbl");
var $trs = $table.find('tr');
// ...
// $($trs) - obviously redundant
Second, it's a bit wasting to go through DOM twice in these lines:
var field = $(row).find('td').eq(0).html();
var value = $(row).find('td').eq(1).html();
I'd rather have it rewritten it like this:
var $tds = $(row).find('td');
var field = $tds.eq(0).html(); // or just $tds[0].innerHTML;
var value = $tds.eq(1).html(); // or just $tds[1].innerHTML;
Upvotes: 9