I am building an application in which I have table with form elements like select, input etc.
All I want is to populate the values selected in form elements to another table.
You can find my code here
JS :
$('button').click(function() {
var rows = $('#table1 tbody tr');
var previewTable = $('#table2 tbody');
previewTable.find('tr').remove();
for (var i = 0; i < rows.length; i++) {
var tr = $('<tr> </tr>');
previewTable.append(tr);
var row_cloned = $(rows[i]).clone();
var cols = rows[i].getElementsByTagName("td");
for (var j = 0; j < cols.length; j++) {
var col_cloned = row_cloned.find('td').clone();
previewTable.find('tr').eq(i).append(col_cloned[j]);
if ($(col_cloned[j]).children().length > 0) {
$(col_cloned[j]).children().each(function(index, item) {
if ($(item).is('select')) {
if ($(item).attr('multiple')) {
var foo = [];
$(item).each(function(i, selected) {
console.log($(selected).val());
foo[i] = $(selected).val();
});
$(col_cloned[j]).text(foo);
} else {
$(col_cloned[j]).text($(item).val());
}
} else if ($(item).is('label')) {
var selected = [];
$(item).find('input:checked').each(function(index, item) {
selected.push($(item).val());
$(col_cloned[j]).append(selected + '<br>');
})
}
})
} else {
$(col_cloned[j]).text($(col_cloned[j]).text());
}
}
}
})
My steps:
- Get table1 and table2
- Count the number of rows in the table1
- Add so many empty rows in the table2
- Get each row in table1
- Count the td in each row of table1
- Find the children in each td
- Check if children is select, input, or just plain text
- If children is select, determine if it is multi-select or single
- Act accordingly for each form elements to copy only values and then append to table2
- finish
All this on a button click COPY
Problem: Somehow managed to get the checked input form element values. But failing to get the values selected in select box.
For multi select box my code:
if ($(item).attr('multiple')) {
var foo = [];
$(item).each(function(i, selected) {
console.log($(selected).val());
foo[i] = $(selected).val();
});
$(col_cloned[j]).text(foo);
}
For single select box :
else {
$(col_cloned[j]).text($(item).val());
}
What is my mistake exactly? Thanks in Advance
Aucun commentaire:
Enregistrer un commentaire