Append Table Array Value To Another Array
I have this code below that popups the cell value whenever the user clicks a specific cell. What I'm currently trying to do is when the user clicks a cell i want that cell value to
Solution 1:
Restructure your code to have a method to redraw
UI and to enable event listeners
:
functionredraw (obj) {
var $header = $('<tr>'),
cols = 0,
bodyString = ''
$.each(obj, function (key, values) {
cols = Math.max(cols, values.length) // find the longest
$header.append($('<th/>').text(key + ': ' + values.length))
})
for (var i = 0; i < cols; i++) { // or use .map, but this is more undertandable for beginners
bodyString += '<tr>'
$.each(obj, function (key, values) {
bodyString += '<td>' +
(values[i] ? values[i] : '') + // ternary - instead of using if/else'</td>'
})
bodyString += '</tr>'
}
$('.fruitsTableClass thead').html($header)
$('.fruitsTableClass tbody').html(bodyString)
}
functionlistener (obj) {
tbl = document.getElementById('fruitsTable')
if (tbl != null) {
for (var i = 0; i < tbl.rows.length; i++) {
for (var j = 0; j < tbl.rows[i].cells.length; j++)
tbl.rows[i].cells[j].onclick = function () {
getval(this)
obj[key2].push(this.innerHTML)
redraw(obj)
listener(obj)
};
}
}
}
functiongetval (cel) {
alert(cel.innerHTML)
}
redraw(obj)
listener(obj)
JSFiddle - https://jsfiddle.net/gnm8wv5f/
Solution 2:
To add rows or cells to a table, you should use the methods insertRow()
and insertCell()
.
Example, if you want to add a cell at the beginning of a row (from w3schools):
var row = document.getElementById("myRow");
var x = row.insertCell(0);
x.innerHTML = "New cell";
Or, to insert at the end:
var x = row.insertCell(row.cells.length);
Using cells.length
you can find the number of cells in a particluar row, in that way you could know where to insert the new cell.
Solution 3:
Try this code.
<html><head><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script>var daraArray=[];
$(document).ready(function(){
$(".classTd").click(function(){
//console.log($(this).html());
daraArray.push($(this).html());
console.log(daraArray);
});
});
</script><styletype="text/css">.classTd{
text-align: center;
}
</style></head><tableid="fruitsTable"class="fruitstableroni skillsTable class"border="1"><thead></thead><tbody><tr><tdclass="classTd"width="10%">1</td><tdclass="classTd"width="10%">2</td><tdclass="classTd"width="10%">3</td></tr><tr><tdclass="classTd"width="10%">4</td><tdclass="classTd"width="10%">5</td><tdclass="classTd"width="10%">6</td></tr><tr><tdclass="classTd"width="10%">7</td><tdclass="classTd"width="10%">8</td><tdclass="classTd"width="10%">9</td></tr></tbody></table></html>
Solution 4:
The other answers here are good but you should definitely try AngularJs. The ng-repeat tag will easily cater your functionality.
Post a Comment for "Append Table Array Value To Another Array"