Fire onkeyup in generated table with contenteditable - javascript

I've got a small problem in my javascript which i am stuck on for a while now.
What i did is :
Create an empty table.
Generate the tr/td tags and values inside the table(from JSON-object).
for (var i = 0 ; i < myList.length ; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0 ; colIndex < columns.length ; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if(colIndex == columns.indexOf("type"))
{
var box$ = $('<td/>');
if(cellValue == "Organisation")
box$.addClass( "uk-badge uk-badge-danger" );
else
box$.addClass( "uk-badge uk-badge-primary" );
box$.html(cellValue);
row$.append(box$);
}
else
{
var box$ = $('<td/>');
box$.html(cellValue);
box$.attr('contenteditable','true');
box$.attr('onkeyup','updateJSON('+colIndex+','+i+')');
row$.append(box$);
}
}
$(selector).append(row$);
}
table looks fine:
td contenteditable="true" onkeyup="updateJSON(3,0)">Timmy/td>
The problem occurs when the table is generated and i edit a field. the 'onkeyup' does not 'fire' while it should. Replacing the 'onkeyup' with an 'onclick' works just fine. I have no clue why this does not work, can anybody help?
var myList = [
{
"id": 1,
"name": "arnold"
},
{
"id": 2,
"name": "hans"
},
{
"id": 3,
"name": "jack"
},
{
"id": 4,
"name": "Peter"
}];
function loadDoc3() {
$("#RelationDataTable tr").remove();
buildHtmlTable('#RelationDataTable');
}
// Builds the HTML Table out of myList.
function buildHtmlTable(selector) {
var columns = addAllColumnHeaders(myList, selector);
for (var i = 0 ; i < myList.length ; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0 ; colIndex < columns.length ; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if(colIndex == columns.indexOf("type"))
{
var box$ = $('<td/>');
if(cellValue == "Organisation")
box$.addClass( "uk-badge uk-badge-danger" );
else
box$.addClass( "uk-badge uk-badge-primary" );
box$.html(cellValue);
row$.append(box$);
}
else
{
var box$ = $('<td/>');
box$.html(cellValue);
box$.attr('contenteditable','true');
box$.attr('onkeyup','updateJSON('+colIndex+','+i+')');
//box$.click(function() {
// alert( "Handler for .keyup() called." );
//});
row$.append(box$);
}
}
$(selector).append(row$);
}
}
var currentcolumns = [];
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(myList) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0 ; i < myList.length ; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1 && key != "id") {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$("#RelationDataTable").append(headerTr$);
currentcolumns = columnSet;
return columnSet;
}
function updateJSON(xx,y)
{
var cellValue = myList[y][currentcolumns[xx]];
alert(document.getElementById("RelationDataTable").rows[y+1].cells[xx].firstChild.nodeValue);
myList[y][currentcolumns[xx]] = document.getElementById("RelationDataTable").rows[y+1].cells[xx].firstChild.nodeValue;
x = 2;
}
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<input id="searchname" type="text" name="InsertSearchname" onkeyup="loadDoc3()"><h2>Search Contact</h2>
<table id="RelationDataTable">
<thead>
</thead>
<tbody>
</tbody>
</table>
</body>

contenteditable="true" should be set for your <td> elements, not on the <table>.
Otherwise the td will not trigger an event.
So add box$.attr('contenteditable','true'); in your loop.

Related

How to change table's cell color created from JSON

I created an HTML table from JSON. The table is university semester map that includes student's ID, year, term and courses required to graduate. I have successful created the table but I want the courses' cell's color depends on courses status. For example, if the student has taken CSCI 135, that cell color should be green. If the course is in progress, the cell color should be yellow. If it needs to be taken, the cell should be red.
My query to get all the courses is
$getCourses = "SELECT * FROM student_majors WHERE student_id = $studID;";
query for courses status
$status = "SELECT * FROM course_status WHERE student_id = $studID;";
the function I used to create the table is following
function CreateTableFromJSON() {
var myCourses = <?php echo $test1; ?> ;
var col = [] ;
var col2 = ["Year","Term","Requirement","","","","","Core","","Credits"] ;
for (var i = 0; i < myCourses.length; i++) {
for (var key in myCourses[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
var table = document.createElement("table");
var tr = table.insertRow(-1);
for (var i = 0; i < col2.length; i++) {
var th = document.createElement("th");
th.innerHTML = col2[i];
tr.appendChild(th);
}
for (var i = 0; i < myCourses.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myCourses[i][col[j]];
}
}
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
I've tried using jquery, js functions to change cell's color based on status of the course but none of those work.
function f_color(){
if (document.getElementByTagName('td').value = 'CSCI135') {
document.getElementByTagName('td').style.background="yellow";
}
}
for (var k = 0; k< col.length; k++){
$("#output td:contains(CSCI135)").attr("style","background-color:green");
$("#output td:contains(CSCI135)").attr("style","background-color:red");
}
I wrote sample snippet to set background color while preparing table itself. You can refer both the ways to set the background color and try to implement it in your scenario.
var myCourses = [{
"Year": 2018,
"Term": 'A',
"Requirement": 'Course',
"Core": 'CSCI135',
"Credits": 120
},
{
"Year": 2019,
"Term": 'A',
"Requirement": 'Course',
"Core": 'CSCI136',
"Credits": 130
},
{
"Year": 2019,
"Term": 'A',
"Requirement": 'Course',
"Core": 'CSCI200',
"Credits": 100
},
{
"Year": 2019,
"Term": 'A',
"Requirement": 'Course',
"Core": 'CSCI123',
"Credits": 140
},
{
"Year": 2019,
"Term": 'A',
"Requirement": 'Course',
"Core": 'abc',
"Credits": 150
}
];
function CreateTableFromJSON() {
var col = [] ;
var col2 = ["Year","Term","Requirement","Core","Credits"] ;
for (var i = 0; i < myCourses.length; i++) {
for (var key in myCourses[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
var table = document.createElement("table");
var tr = table.insertRow(-1);
for (var i = 0; i < col2.length; i++) {
var th = document.createElement("th");
th.innerHTML = col2[i];
tr.appendChild(th);
}
for (var i = 0; i < myCourses.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = myCourses[i][col[j]];
/* 1st Way*/
if(col[j] == 'Credits'){
if(myCourses[i][col[j]] > 130 ){
tabCell.style.background = 'green';
}
else if(myCourses[i][col[j]] < 130 ){
tabCell.style.background = 'red';
}
else {
tabCell.style.background = 'yellow';
}
}
/*2nd Way */
if(col[j] == 'Core'){
if(myCourses[i][col[j]] == 'CSCI135' ){
tabCell.className = 'success';
}
else if(myCourses[i][col[j]] == 'CSCI123' ){
tabCell.className = 'completed';
}
else {
tabCell.className = 'inprocess';
}
}
}
}
var divContainer = document.getElementById("showData");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
CreateTableFromJSON();
.success{
background: green;
}
.completed{
background: red;
}
.inprocess{
background: yellow;
}
<div id="showData"></div>
for (var i = 0; i < myCourses.length; i++) {
tr = table.insertRow(-1); // ADD JSON DATA TO THE TABLE AS ROWS.
for (var j = 0; j < col2.length; j++) {
var tabCell = tr.insertCell(-1);
var done_course = <?php echo json_encode($done_course); ?> ;
var pending_course = <?php echo json_encode($pending_course); ?> ;
var progress_course = <?php echo json_encode($progress_course); ?> ;
tabCell.innerHTML = myCourses[i][col[j]];
if (done_course.includes(myCourses[i][col[j]])) {
tabCell.className = 'success';
} else if (pending_course.includes(myCourses[i][col[j]])) {
tabCell.className = 'completed'; }
else {
tabCell.className = 'inprocess'; }
}
}

How do I display only details of Linda using JSON

i would like to display only details of Linda using JSON. However, I am clueless on how to do it. Need some advice, thanks!
The output should show the updated table with only "Linda" instead of my current output.
Actual question:
Using JSON, modify the mobile of Linda to 88885555, and display only the details of Linda.
My employees object is supposed to be from .json file but i couldnt find the format to insert into this post. Hence, i combined it into my .js file.
var employees = [
{
"Name": "Tony",
"Mobile": 99221111,
"Email": "tony#json.com"
},
{
"Name": "Linda",
"Mobile": 98981111,
"Email": "linda#json.com"
},
{
"Name": "Patrick",
"Email": "patrick#json.com"
},
{
"Name": "Isabella",
"Mobile": 99552222
}
];
employees[1].Mobile = 88885555;
function buildHtmlTable() {
var columns = addAllColumnHeaders(employees);
for (var i = 0; i < employees.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = employees[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
row$.append($('<td/>').html(cellValue));
}
$("#employeeTable").append(row$);
}
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(employees) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < employees.length; i++) {
var rowHash = employees[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$("#employeeTable").append(headerTr$);
return columnSet;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body onLoad="buildHtmlTable()">
<table id="employeeTable" border="1"></table>
</body>
You can create a function that accepts an "employee name", .not() and .is() to match any <td> elements within the <tr> where .textContent is equal to the argument passed to the function, chain .hide() to set the display of the matched elements to "none".
To display all <tr> elements you can use $("#employeeTable tr").show().
Substituted using jQuery(function(){}) for onload attribute event handler at <body> element.
var employees = [{
"Name": "Tony",
"Mobile": 99221111,
"Email": "tony#json.com"
},
{
"Name": "Linda",
"Mobile": 98981111,
"Email": "linda#json.com"
},
{
"Name": "Patrick",
"Email": "patrick#json.com"
},
{
"Name": "Isabella",
"Mobile": 99552222
}
];
employees[1].Mobile = 88885555;
function buildHtmlTable() {
var columns = addAllColumnHeaders(employees);
for (var i = 0; i < employees.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = employees[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
row$.append($('<td/>').html(cellValue));
}
$("#employeeTable").append(row$);
}
}
// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(employees) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < employees.length; i++) {
var rowHash = employees[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$("#employeeTable").append(headerTr$);
return columnSet;
}
<!DOCTYPE html>
<html>
<head>
<title>Task 1</title>
<!-- using of jquery, calling external js file -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<table id="employeeTable" border="1">
</table>
<script>
$(function() {
buildHtmlTable();
function hideRow(employeeName) {
return $("#employeeTable tr").not(function(index, element) {
return $(element.cells).is(function(i, el) {
return el.textContent === employeeName
});
}).hide();
}
hideRow("Linda");
});
</script>
</body>
</html>
If I understood your question correctly you could do something like I did below. I used setTimeout so you can see the transition from your original output to the updated output:
function buildTable(arr) {
let html = "<table border='1' style='width: 100%'>";
for (let i = 0; i < arr.length; i++) {
html += `<tr>
<td>${arr[i].Name || ''}</td>
<td>${arr[i].Mobile || ''}</td>
<td>${arr[i].Email || ''}</td>
</tr>`;
}
html += "</table>";
return html;
}
function init() {
const LINDA_IDX = 1;
container.innerHTML = buildTable(employees);
setTimeout(function() { //
//Update Linda's phone number
employees[LINDA_IDX].Mobile = 88885555;
//Show just Linda in the table
container.innerHTML = buildTable([employees[LINDA_IDX]])
}, 2000);
}
var employees = [{
"Name": "Tony",
"Mobile": 99221111,
"Email": "tony#json.com"
}, {
"Name": "Linda",
"Mobile": 98981111,
"Email": "linda#json.com"
}, {
"Name": "Patrick",
"Email": "patrick#json.com"
}, {
"Name": "Isabella",
"Mobile": 99552222
}];
var container = document.querySelector('#container');
init();
After 2 seconds setTimeout will execute showing Linda's updated info:<br />
<div id="container"></div>

how to dynamically add multiple checkboxes to an html table?

I want to dynamically add checkboxes to multiple rows in an html table, without having to add input type ="checkbox" for each . Is this possible?
The code snippet for making the table and a function 'check()' to add check boxes is given below...but it does not work. please help.
// Builds the HTML Table out of myList json data.
function buildHtmlTable(myList) {
var columns = addAllColumnHeaders(myList);
for (var i = 0; i < myList.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
row$.append($('<td/>').html(cellValue));
}
$("#excelDataTable").append(row$);
}
}
// Adds a header row to the table and returns the set of columns.
function addAllColumnHeaders(myList) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
//check();
}
// check();
}
//check();
}
$("#excelDataTable").append(headerTr$);
return columnSet;
check();
}
function check() {
for (var i = 0; i < myList.length; i++) {
$('<input />', {
type: 'checkbox',
id: 'id' + i,
})
.appendTo("#excelDataTable");
}
}
You can add the checkboxes after the table is created.
Below, you can see the updated code. Your table creation works perfect. But you were trying to append the checkboxes to the table itself, not td elements.
In $(document).ready function below, you can see that I create the table first and after that call check() function. It basicly creates a new checkbox for each row, wraps it in a td and put that into the row.
I also added a change event method for the first checkbox to control all the others.
// Builds the HTML Table out of myList json data.
function buildHtmlTable(myList) {
var columns = addAllColumnHeaders(myList);
for (var i = 0; i < myList.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
row$.append($('<td/>').html(cellValue));
}
$("#excelDataTable").append(row$);
}
}
// Adds a header row to the table and returns the set of columns.
function addAllColumnHeaders(myList) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
//check();
}
// check();
}
//check();
}
$("#excelDataTable").append(headerTr$);
return columnSet;
//check();
}
function check() {
// foreach row in the table
// we create a new checkbox
// and wrap it with a td element
// then put that td at the beginning of the row
var $rows = $('#excelDataTable tr');
for (var i = 0; i < $rows.length; i++) {
var $checkbox = $('<input />', {
type: 'checkbox',
id: 'id' + i,
});
$checkbox.wrap('<td></td>').parent().prependTo($rows[i]);
}
// First checkbox changes all the others
$('#id0').change(function(){
var isChecked = $(this).is(':checked');
$('#excelDataTable input[type=checkbox]').prop('checked', isChecked);
})
}
$(document).ready(function() {
var myList = [{
"ASN": "AS9498 BHARTI Airtel Ltd.",
"COUNTRY": "IN",
"IP": "182.72.211.158\n"
}, {
"ASN": "AS9874 StarHub Broadband",
"COUNTRY": "SG",
"IP": "183.90.37.224"
}, {
"ASN": "AS45143 SINGTEL MOBILE INTERNET SERVICE PROVIDER Singapore",
"COUNTRY": "SG",
"IP": "14.100.132.200"
}, {
"ASN": "AS45143 SINGTEL MOBILE INTERNET SERVICE PROVIDER Singapore",
"COUNTRY": "SG",
"IP": "14.100.134.235"
}]
buildHtmlTable(myList);
check();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="excelDataTable"></table>

Fix the first and the second column of dynamic table generated according to JSON file

Define empty table in HTML file, and append thead and tbody in js file, fill the td content in js file according to data read from JSON file.
Question: How to fix the 1st and 2nd column of this dynamic table?
It is just an example. You can try this.
var myList = [
{ "name": "abc", "age": 50 },
{ "age": "25", "hobby": "swimming" },
{ "name": "xyz", "hobby": "programming" }
];
function buildHtmlTable(selector) {
var columns = addAllColumnHeaders(myList, selector);
for (var i = 0; i < myList.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = myList[i][columns[colIndex]];
if (cellValue == null) cellValue = "";
row$.append($('<td/>').html(cellValue));
}
$(selector).append(row$);
}
}
function addAllColumnHeaders(myList, selector) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$(selector).append(headerTr$);
return columnSet;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onLoad="buildHtmlTable('#excelDataTable')">
<table id="excelDataTable" border="1">
</table>
</body>

JavaScript reading data into an array from a dynamic table of textfields

I'm dynamically creating a table using an HTML table and JavaScript Functions attatched to button clicks. I now want to take the data and store it into multidimensional array (if possible) using another button named finished. I'm having trouble even getting started with the last method to save it into array. I can't figure out how to retrieve the text data.
Here is my current HTML code.
<head>
<title>TableTest</title>
<script src="/javascript/func.js"></script>
</head>
<body>
<form>
<div id="Input">
<INPUT class="form-button" id="AddRow" type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT class="form-button" id="DeleteRow" type="button" value="Delete Row(s)" onclick="deleteRow('dataTable')" />
<INPUT class="form-button" id="Finished" type="button" value="Finished" onclick="gatherData('dataTable')" />
<table id="dataTable" border="1" style="width:200px" id="mytable" align="center" cellspacing="3" cellpadding="4">
<th>Select</th>
<th>Text1</th>
<th>Text2</th>
<th>Text3</th>
<tr>
<td><INPUT type="checkbox" name="chk"/></td>
<td><INPUT type="text" name="text1"/></td>
<td><INPUT type="text" name="txt2"/></td>
<td><INPUT type="text" name="txt3"/></td>
</tr>
</table>
</div>
</form>
</body>
Here is my JavaScript file:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 2) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
function gatherData(){
//Tests
var table = document.getElementById('dataTable');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
alert(rowCount);
alert(row);
alert(colCount);
}
I reworked TameBadger's answer to build the array by row instead of by column. I also added a check to see if the given cell has a value before referencing it. In my case, not all cells have values.
var table = document.getElementById('mainTable');
if (table === null)
return;
if (table.rows[0].cells.length <= 1)
return;
var tblData = [];
//Put a RowNumber name and values placeholder for the number of rows we have.
for (r = 0; r < table.rows.length; r++)
{
//Debug
//console.log(" row: ", r);
tblData.push({
name: "RowNumber" + r,
items: []
});
//Get the cells for this row.
var cells = table.rows[r].cells;
//Loop through each column for this row and push the value...
for (c = 0; c < cells.length; c++)
{
var inputElem = cells[c].children[0];
var tmpInputElem;
if (inputElem == null)
{
tmpInputElem = "";
}
else
{
tmpInputElem = inputElem.value
}
//Debug
//console.log(" row-cel: ", r, "-", c, " ", inputElem);
tblData[r].items.push(
{
//Comment out the type for now...
//inputType: inputElem.getAttribute('type'),
inputValue: tmpInputElem
});
}
}
//Debug
//printData(tblData);
I tried to keep it simple, and also jQuery clean, so to speak.
var data = [];
function gatherData() {
var table = document.getElementById('dataTable');
for (r = 1; r < table.rows.length; r++) {
var row = table.rows[r];
var cells = row.cells;
for (c = 0; c < cells.length; c++) {
var cell = cells[c];
var inputElem = cell.children[0];
var isInput = inputElem instanceof HTMLInputElement;
if (!isInput)
return;
var value = inputElem.value;
var isCheckbox = inputElem.getAttribute('type') == 'checkbox';
if (isCheckbox)
value = inputElem.checked;
var rowData = {};
rowData.inputType = inputElem.getAttribute('type');
rowData.inputValue = value;
data.push(rowData);
}
}
}
function startExec() {
gatherData();
for (i = 0; i < data.length; i++) {
console.log(data[i].inputType);
console.log(data[i].inputValue);
}
}
//just wait for the dom to load, and then execute the function for testing
document.addEventListener("DOMContentLoaded", startExec, false);
2nd Revision
function getData() {
var table = document.getElementById('dataTable');
if (table === null)
return;
if (table.rows[0].cells.length <= 1)
return;
var data = [];
for (l = 0; l < table.rows[0].cells.length; l++) {
data.push({
items: [],
name: "ColumnNumber" + l
});
}
for (i = 1; i < table.rows.length; i++) {
var cells = table.rows[i].cells;
for (c = 0; c < cells.length; c++) {
var inputElem = cells[c].children[0];
data[c].items.push({
inputType: inputElem.getAttribute('type'),
inputValue: inputElem.value
});
}
}
printData(data);
}
function printData(data) {
for (i = 0; i < data.length; i++) {
for (k = 0; k < data[i].items.length; k++) {
console.log(data[i].items[k].inputValue);
}
}
}
document.addEventListener("DOMContentLoaded", getData(), false);
It's great that you're starting off and doing the table manipulation yourself, and I would recommend continuing that, if you want to peak into a bigger codebase I would recommend checking out jTable's. Even though it's a jQuery plugin, you'll still be able to learn something from looking at the code structure for handling all the logic surrounding building a table according to a dataset and adding records etc.
Is this what you are looking for?
JSFIDDLE
$(document).ready(function(){
$('#Finished').click(function(){
var my_arr=[];
$('td').each(function(){
if ($(this).children().is(':checkbox') )
{
if($(this).children().prop('checked'))
{
my_arr.push($(this).children().val());
}
}else{
my_arr.push($(this).children().val());
}
})
console.log(my_arr);
})
})

Categories

Resources