Reputation: 2123
I want to create a dynamic table according to assigned array as below image:
My code:
HTML
<table id="selectTable" class="m-table">
<thead>
<tr>
<th>Products</th>
<th>Range</th>
</tr>
</thead>
</table>
JQUERY
function drawTable(data) {
var dateTable = $('#selectTable');
selectEl = $('<select>'),
selectVal = [
{val : 1, text: '1'},
{val : 2, text: '2'},
{val : 3, text: '3'},
{val : 4, text: '4'},
{val : 5, text: '5'}
];
$(selectVal).each(function() {
selectEl
.append($('<option>')
.attr('value',this.val)
.text(this.text));
});
dateTable.children('tbody').empty();
$.each(data,function(k,v){
var row = $('<tr />',{'class':'row-'+k});
dateTable.append(row);
row.append($('<td />').append(v));
row.append($('<td />').append(selectEl + ' ' + selectEl ));
});
}
var a = ['Product-1','Product-2','Product-3','Product-4','Product-5'];
drawTable(a);
Table and selectbox will create dynamically and append to table each row. How can I do this?
Upvotes: 1
Views: 2545
Reputation: 2123
I append two selectbox to each row with the following edit;
dateTable.append(row);
row.append($('<td />').append(v));
row.append($('<td />').append(selectEl));
row.children('td:nth-child(2)').append(selectEl.clone());
Upvotes: 0
Reputation: 1800
The problem is $('select') is the same instance and hence can only append to one row. You need to clone before append to the row.
Refer to http://jsfiddle.net/hutingung/dsjLT/3/
Snippet of the code
$.each(data,function(k,v){
var row = $('<tr />',{'class':'row-'+k});
dateTable.append(row);
row.append($('<td />').append(v));
//you are refer to same instance of selectEL
//row.append($('<td />').append(selectEl));
//Use clone to append
selectEl.clone().appendTo(row);
});
Upvotes: 0
Reputation: 326
Not sure you can reuse the selectEl that way. I'd try to recreate it for each row. This works (though it needs cleanup):
function drawTable(data) {
var dateTable = $('#selectTable');
dateTable.children('tbody').empty();
$.each(data,function(k,v){
var selectEl = $('<select>'),
selectVal = [
{val : 1, text: '1'},
{val : 2, text: '2'},
{val : 3, text: '3'},
{val : 4, text: '4'},
{val : 5, text: '5'}
];
$(selectVal).each(function() {
selectEl
.append($('<option>')
.attr('value',this.val)
.text(this.text));
});
var row = $('<tr />',{'class':'row-'+k});
dateTable.append(row);
row.append($('<td />').append(v));
row.append($('<td />').append(selectEl));
});
}
var a = ['Product-1','Product-2','Product-3','Product-4','Product-5'];
drawTable(a);
Upvotes: 3