Is option to assign ID to every checkbox inside dynamic table - javascript

This is my dynamic table
After clicking button it generate table based on input.
$(function () {
$("#btnGenerate").click(function () {
var textarea = document.getElementById("inglist");
var lines = textarea.value.replace(/\r\n/g,"\n").split(/:|,|\n/);
var lines2 = textarea.value.split(/(\d+(?:\.\d+)?)/);
lines.forEach((o, i) => o.id = i + 1);
var array1=new Array();
for (var i = 1; i < lines .length; i++) {
array1.push(lines [i].replace(/\[.*?\]/g, ''));}
const results = [];
array1.forEach(line => {
const filtered = line.split(/([\s\w]+)\s(\d+(?:\.\d+)?)(%?)\s*(\[\d\])?/g).filter(Boolean);
results.push(filtered);
});
var build = new Array();
build.push(["ING name:", "Total:","unit", "Count it?:","x2?"]);
var table1 = $("<table />");
for(var i=0;i<results.length;i++){
build.push(results[i]);
}
var countColumns = build[0].length;
console.log(countColumns);
var tables = $("<table /><class='form-control input-md'>");
//Add the header row.
var rows = $(tables[0].insertRow(-1));
for (var i = 0; i < countColumns; i++) {
var headerCell = $("<th /><class='form-control input-md'>");
headerCell.html(build[0][i]);
rows.append(headerCell);
}
//Add the data rows.
for (var i = 1; i < build.length; i++) {
row = $(tables[0].insertRow(-1));
for (var j = 0; j < countColumns; j++) {
var cell = $('<td><input type="checkbox"/>');
cell.html(build[i][j]);
row.append(cell);
}
}
var dvTable1 = $("#dvTable1");
dvTable1.html("");
dvTable1.append(tables);
});
How i can assign dynamic ID to every checkbox ?
And then how to filter only rows where is tick checkbox in 3rd column ( count in?: )

Related

To create a custom table by getting values from a dynamicaly created table

what I want is on save click to show another table like below where the second column(Questions) has sub-columns depending maximum L value a row has:
unit Question
unit1 23(L1)
unit2 23(L3)
unit3 24(L3)
unit4 6(L2)
unit4 10(L4)
unit5 7(L1)
unit5 10(L6)
unit6 10(L2)
unit 7(L4)
var x = [];
function getval() {
var trs = $('#DyanmicTable3 tr:not(:first-child):not(:nth-last-child(2)):not(:last-child)');
var trs1 = $('#DyanmicTable3 tr:last-child');
var lastTotalElement = $('#DyanmicTable3 tr:nth-last-child(2)');
console.log(trs1);
for (let i = 2; i <= 7; i++) {
const total = Array.from(trs)
.reduce((acc, tr) => x.push(Number(tr.children[i].textContent)), 0);
;
}
console.log(JSON.stringify(x));
}
this is wt i got so far getting values in an array
function GenerateTable() {
var grid = new Array();
grid.push(["Unit", "Marks", "Bloom Level"]);
var tb = $('#DyanmicTable3:eq(0) tbody ');
tb.find("tr:not(:first-child):not(:nth-last-child(2)):not(:last-child)").each(function (index, element) {
var colValtst;
$(element).find('th:not(:first-child):not(:nth-last-child(2)):not(:last-child)').each(function (index, element) {
colValtst = $(element).text();
});
$(element).find('td').each(function (index, element) {
var colVal = $(element).text();
let y = $(element).index();
if (colVal != '') {
console.log(" Value in " + colValtst + " : " + colVal.trim() + " L" + y);
//add grid here
grid.push([colValtst, colVal.trim(), "L" + y]);
}
});
});
//Build an array containing Customer records.
// $('#save').attr('href', 'AddQuestions.aspx?val1=' + grid + '');
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1";
//Get the count of columns.
var columnCount = grid[0].length;
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = grid[0][i];
row.appendChild(headerCell);
}
//Add the data rows.
for (var i = 1; i < grid.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < columnCount; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = grid[i][j];
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);

Can I create dropdown rows dynamically for a table using html and Javascript

I've created a table dynamically, but now I want to create a dropdown row on demand. I have an onclick handler for each row. Upon clicking, this row should drop something downward (like a hidden div but unfortunately these cannot be easily created in a dynamic setting, as there's not a way to assign a unique id at row creation. Is this even possible in Javascript/jQuery? or, preferably, twitter bootstrap?
function buildHtmlTable(portalData, tablename) {
var columns = [];
var headerTr$ = $('<tr/>');
var n = 0;
if (tablename == "order-table") {
document.getElementById("dist-name").innerText = JSON.parse(JSON.stringify(portalData[0], null, 2))["Company Name"];
n = 1;
}
for (var i = 0 ; i < portalData.length ; i++) {
var rowHash = portalData[i];
for (var key in rowHash) {
if ($.inArray(key, columns) == -1) {
columns.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$('#' + tablename).append(headerTr$);
for (i = 0 ; i < portalData.length ; i++) {
var row$ = $('<tr/>');
for (var colIndex = n ; colIndex < columns.length ; colIndex++) { // n is how many columns to drop, based on table name
var cellValue = portalData[i][columns[colIndex]];
if (cellValue == null) {
cellValue = "";
}
row$.append($('<td/>').html(cellValue));
}
$('#' + tablename).append(row$);
}
// Drop unnecessary columns
for(i = 0 ; i<n; i++) {
$("#order-table").find('td,th').first().remove();
}
if (tablename == "order-table") {
var tablerows = document.getElementsByTagName('tr');
for (var x in tablerows) {
tablerows[x].classList.add("clickable");
tablerows[x].setAttribute(data-toggle,"collapse");
tablerows[x].setAttribute(data-target,"");
}
}
}

How "tblGene()" call on JavaScript page.I am want to call on HTML page using onclick.. Without click this Json table show on my web page

How tblGene() call on JavaScript page. I do not want to call on HTML page using onclick. Without click, this JSON table show on my web page. Please help me. When page was loaded this JSON table on my web page. I do not want to use input box for click.
<input type="button" onclick="tblGene()" value="Click Here to Generate Table" style="width:100% height:100%" />
<div id="showData"></div>
var people, asc1 = 1;
function tblGene() {
var data = [{"rollno":1234,'name': "jetta",'marks': 600,'percentage': 1222,'bestscore': 99},{"rollno":2341,'name': "jetta",'marks': 700,'percentage': 1222,'bestscore': 100},{"rollno":3421,'name': "jetta",'marks': 500,'percentage': 1222,'bestscore': 90},{"rollno":4321,'name': "jetta",'marks': 400,'percentage': 1222,'bestscore': 95},{"rollno":2043,'name': "jetta",'marks': 550,'percentage': 1222,'bestscore': 80},];
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
tbody.id = "people";
var tbl = document.createElement("table");
tbl.id = "tblSample";
var col = [];
for (var i = 0; i < data.length; i++) {
for (var colHdr in data[i]) {
if (col.indexOf(colHdr) === -1) {
col.push(colHdr);
}
}
}
var tr = tbl.insertRow(-1);
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
th.dataset.key = i;
tr.appendChild(th);
}
thead.appendChild(tr);
for (var i = 0; i < data.length; i++) {
tr = tbl.insertRow(-1);
for (var j = 0; j < col.length; j++) {
var td = document.createElement("td");
var tabCell = tr.insertCell(-1);
tabCell.innerHTML = data[i][col[j]];
}
tbody.appendChild(tr);
}
tbl.appendChild(thead);
tbl.appendChild(tbody);
var divCntr = document.getElementById("showData");
divCntr.innerHTML = "";
divCntr.appendChild(tbl);
thead.addEventListener("click", function(event) {
var key = event.target.dataset.key;
people = document.getElementById("people");
sort_tbl(people, key, asc1);
});
function sort_tbl(tblSample, key, asc) {
var rows = tblSample.rows,
rlen = rows.length,
arr = new Array();
for (var i = 0; i < rlen; i++) {
var cells = rows[i].cells;
var clen = cells.length;
arr[i] = new Array();
for (var j = 0; j < clen; j++) {
arr[i][j] = cells[j].innerHTML;
}
}
arr.sort(function(x, y) {
if (isNaN(x[key]) && isNaN(y[key])) {
var a = String(x[key]).toUpperCase();
var b = String(y[key]).toUpperCase();
if (a > b)
return 1
if (a < b)
return -1
return 0;
} else {
return x[key] - y[key];
}
});
for (i = 0; i < rlen; i++) {
rows[i].innerHTML = "<td>" + arr[i].join("</td><td>") + "</td>";
}
}
}
Just remove the () from you onclick handler, like this onclick="tblGene".
If you leave the (), you're executing the function as soon as the <input> element is loaded - in your case on page load.

how to add checkboxes in cells of first column of HTML table?

I am working on an app development which will read through my mailbox and list all the unread e-mails in a HTML table on my web-app upon click of a button. Below is the code which I have made while researching through google which solves for the purpose.
<!DOCTYPE html>
<html>
<body>
<button onclick="groupFunction()">Click me</button>
<table id="tblContents">
<tr onclick="tableClickTest()">
<th>Sender</th>
<th>Sent_Date</th>
<th>Received_By</th>
<th>Received_Date</th>
<th>Subject</th>
</tr>
</table>
<script>
function RowSelection()
{
var table = document.getElementById("tblContents");
if (table != null) {
for (var i = 0; i < table.rows.length; i++) {
for (var j = 0; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
};
}
}
}
function tableText(tableCell) {
alert(tableCell.innerHTML);
}
function PopulateTable()
{
var objOutlook = new ActiveXObject("Outlook.Application");
var session = objOutlook.Session;
//alert(session.Folders.Count)
for(var folderCount = 1;folderCount <= session.Folders.Count; folderCount++)
{
var folder = session.Folders.Item(folderCount);
//alert(folder.Name)
if(folder.Name.indexOf("Premanshu.Basak#genpact.com")>=0)
{
for(var subFolCount = 1; subFolCount <= folder.Folders.Count; subFolCount++)
{
var sampleFolder = folder.Folders.Item(subFolCount);
//alert(sampleFolder.Name)
if(sampleFolder.Name.indexOf("test1")>=0)
{
for(var itmCount = 1; itmCount <= sampleFolder.Items.Count; itmCount++)
{
var itm = sampleFolder.Items.Item(itmCount);
if(!itm.UnRead)
continue;
var sentBy = itm.SenderName;
var sentDate = itm.SentOn;
var receivedBy = itm.ReceivedByName;
var receivedDate = itm.ReceivedTime;
var subject = itm.ConversationTopic;
// var contents = itm.Body;
var tbl = document.getElementById("tblContents");
if(tbl)
{
var tr = tbl.insertRow(tbl.rows.length);
// tr.onclick(tableClickTest())
if(tbl.rows.length%2 != 0)
tr.className = "alt";
var tdsentBy = tr.insertCell(0);
var tdsentDate = tr.insertCell(1);
var tdreceivedBy = tr.insertCell(2);
var tdreceivedDate = tr.insertCell(3);
var tdsubject = tr.insertCell(4);
// var tdcontents = tr.insertCell(5);
tdsentBy.innerHTML = sentBy;
tdsentDate.innerHTML = sentDate;
tdreceivedBy.innerHTML = receivedBy;
tdreceivedDate.innerHTML = receivedDate;
tdsubject.innerHTML = subject;
// tdcontents.innerHTML = contents;
}
//itm.UnRead = false;
}
break;
}
}
break;
}
}
return;
}
function groupFunction()
{
PopulateTable()
RowSelection()
}
</script>
</body>
</html>
The thing that I am now looking for and is unable to do is how do I add a checkbox in the first column in each row. Also upon checking this checkbox the entire row should get highlighted so that I can perform specific task on all the selected items.
As far as I have understood your code, your first column's data is being set as:
tdsentBy.innerHTML = sentBy;
So in the same line, you can add textbox as a string as:
var cbox = "<div class='select-box'>
<input type='checkbox' name='selectBox' class='select-row'>
</div?>"
tdsentBy.innerHTML = cbox + sentBy;
In this way, a checkbox will always be available in first column of every row.
Now in RowSelection function, to bind event you can do something like:
var checkBox = table.rows[i].cells[j].querySelector(".select-row");
checkBox.addEventListener("click",function(evt){
});

problems with creating tables/rows using pop/push

I'm trying to create a table in HTML using javascript. It has an add button that add's new rows and a delete button that removes rows. It looks like this :
the numbers are the ids
<table id = "table1" border = 2>
<tr>
<td> <img id="add" src="images/add_over.png" onclick=help() /> </td>
</tr>
</table>
Basically I'm trying to delete the whole table and recreate it with one row less.
var array1 = new Array();
function help() {
addRow();
push();
}
function addRow() {
var tableId= "table1";
var number= array1.length;
var newRow = document.getElementById(tableId).insertRow(number+ 1);
var newData = document.createElement("td");
var newDiv= document.createElement("div");
newDiv.innerHTML = array1.length;
newData.appendChild(newDiv);
var newCellDeleteButton = document.createElement("td");
var deleteButtonImg = document.createElement('img');
deleteButtonImg.id = number;
deleteButtonImg.border = '0';
deleteButtonImg.src = "images/delete_up.png";
deleteButtonImg.onmouseover = function() {
this.src = 'images/delete_over.png';
};
deleteButtonImg.onmouseout = function() {
this.src = 'images/delete_up.png';
};
deleteButtonImg.onclick = function() {
deleteRow(number);
};
newCellDeleteButton.appendChild(deleteButtonImg);
newRow.appendChild(newRow);
newRow.appendChild(newCellDeleteButton);
}
function deleteRow(rowID) {
var tempHelpRow = array1.length;
pop(rowID);
for (var i = 1; i <= tempHelpRow ; i++) {
document.getElementById("table1").deleteRow(1);
}
for (var i = 0; i <= array1.length; i++) {
addRow();
}
}
function pop(ID) {
array1.pop(ID);
}
function push() {
var test = new objectt();
array1.push(test);
}
function objectt() {
}
the problem is, that if i try to delete one row it deletes everything.

Categories