how to dynamically add multiple checkboxes to an html table? - javascript

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>

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'; }
}
}

Filter Table Data, and Remove Filtered Column

I am currently using:
function searchNotes() {
const url = "http://localhost:2609/api/notes"
$.ajax({
url: url,
type: 'GET',
success: function (notesList) {
console.log(notesList)
// EXTRACT VALUE FOR HTML HEADER.
var col = [];
for (var i = 0; i < notesList.length; i++) {
for (var key in notesList[i]) {
if (col.indexOf(key) === -1 && (key === 'title' || key === 'content' || key == 'category' || key == 'categoryId')) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < notesList.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = notesList[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("listNotes");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
});
}
to create a html table using jquery. The table looks like this:
I want to filter the table by categoryId, as chosen in the dropdown at the top, then I want to remove the categoryId column. Any ideas how I could achieve this?
You need to use .sort() on the notesList object, something like this:
notesList.sort(function(a, b) {
return a.categoryId - b.categoryId;
});
Put it before appending the values to the html.
To 'remove' the categoryId column is very simple: Just remove the followingen bit from the if statement:
|| key == 'categoryId'
So your end result is something like this:
function searchNotes() {
const url = "http://localhost:2609/api/notes"
$.ajax({
url: url,
type: 'GET',
success: function (notesList) {
notesList.sort(function(a, b) {
return a.categoryId - b.categoryId;
});
// EXTRACT VALUE FOR HTML HEADER.
var col = [];
for (var i = 0; i < notesList.length; i++) {
for (var key in notesList[i]) {
if (col.indexOf(key) === -1 && (key === 'title' || key === 'content' || key == 'category')) {
col.push(key);
}
}
}
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
// CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
var tr = table.insertRow(-1); // TABLE ROW.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th"); // TABLE HEADER.
th.innerHTML = col[i];
tr.appendChild(th);
}
// ADD JSON DATA TO THE TABLE AS ROWS.
for (var i = 0; i < notesList.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = notesList[i][col[j]];
}
}
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("listNotes");
divContainer.innerHTML = "";
divContainer.appendChild(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>

Fire onkeyup in generated table with contenteditable

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.

how to get checkbox from multiple cells in html table?

I have dynamic html table and every cell have one checkbox. I want to get the selected checkbox if the user select from multiple checkbox from different row.
function GetAllChecked() {
var chkedshid = new Array();
var rows = new Array();
rows = document.getElementById("Tbl_Id").getElementsByTagName("tr");
trcount = rows.length;
for (var i = 0; i < rows.length; i++) {
trid = rows[i].id;
chkedshid = chkedshid + chkedshid
if (inputList = document.getElementById(trid).getElementsByTagName("input")) {
for (var n = 0; n < inputList.length; n++) {
if (inputList[n].type == "checkbox") {
if (inputList[n].checked == true) {
chkedshid[n] = inputList[n].id;
}
}
}
}
}
document.getElementById('Hidden_CellSelected').value = chkedshid.join();
document.getElementById("BtnSav2Cart").click();
}
why why this function return just last selected checkbox for last row in loop????
i need the all selected checkbox for all rows!!!!!!!
Assuming you are using jQuery.
Then you can simply do -
$("#myTableId input:checked")
If your checkbox have specific class then you can also do -
$("#myTableId .specificCheckboxClass:checked")
On some Button click try to execute this code
var checkedTransactions = $("input:[name='idofcheckboxe']:checked").map(function () {
return $(this).val();
}).get();
var will return all id of check boxes which are selected
thanks all i solve the problem:
function GetAllChecked() {
var chkedshid = new Array();
var rows = new Array();
rows = document.getElementById("Tbl_Id").getElementsByTagName("tr");
trcount = rows.length;
var totlchk = new Array();
for (var i = 0; i < rows.length; i++) {
trid = rows[i].id;
if (inputList = document.getElementById(trid).getElementsByTagName("input")) {
for (var n = 0; n < inputList.length; n++) {
if (inputList[n].type == "checkbox") {
if (inputList[n].checked == true) {
chkedshid[n] = inputList[n].id;
}
}
}
totlchk = totlchk.concat(chkedshid.join());
}
}
document.getElementById('myHiddenfield').value = totlchk.join();
document.getElementById("BtnSav2Cart").click();
}
var table = document.getElementById("mytable");
checkbox = table.getElementsByTagName("input");
for(var indexCheckbox = 1; indexCheckbox<checkbox.length; indexCheckbox++){
if(checkbox[indexCheckbox].checked){
//do something
}
}

Categories

Resources