I am having a huge brain fart with efficiency right now.
The idea here is if I have a static table
(unfortunately formatted this way with the data I've received), how would I appropriately append
a select option dropdown
with every value from the table categorized easily?
I currently have it working, but it seems as if I could make it more efficient than my current statement. I have the feeling with all the DOM
manipulation I have going on, if I tried to use this on a table with thousands of items it would lag the browser. Let's get to the code.
JS Fiddle: http://jsfiddle.net/z2V2p/1/
HTML:
<table id='data'>
<tr>
<td>Item 1</td>
<td>Value 1</td>
<td>Prop 1</td>
</tr>
<tr >
<td>Item 2</td>
<td>Value 2</td>
<td>Prop 2</td>
</tr>
<tr >
<td>Item 3</td>
<td>Value 3</td>
<td>Prop 3</td>
</tr>
</table>
<select id="item"></select>
<select id="value"></select>
<select id="prop"></select>
Javascript/jQuery:
$('tr td').each(function() {
var $this = $(this);
var text = $this.text();
var select = '<option value="'+text+'">'+text+'</option>';
switch($this.index()){
case 0:
$('#item').append(select);
break;
case 1:
$('#value').append(select);
break;
case 2:
$('#prop').append(select);
break;
default:
alert('Unexpected Error.');
}
});
So, I suppose the questions are:
- Is there any easy way to make this more efficient?
- Perhaps utilizing an
array
to cache the values, andappend
them from that? - Or is there an easier method of using
index
of the items instead of myswitch case
that would render quicker and be more expandable for furthertd
s if they were implemented?
I appreciate all of the help.
I've considered just ultimately converting the darn table to a json
object, but I figured I'd reach out here first. (this will deploy thousands of times per week, and I don't want anything hard coded.)
Looking for a way to add every TD
in its index
of its TR
to be appended to an existing select option
based on the index
value.