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

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){
});

Related

Is option to assign ID to every checkbox inside dynamic table

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?: )

can't use If - Else element exists in Javascript

I wrote a JS function to create a table in html and JS I want to click submit and after that the table to be created but I dont want the Submit button to create another table if clicked again
I tried to use IF - Else statements in the function but It's not working
code:
Button:
document.getElementById("btn_submit").addEventListener("click",sizeGrid)
function
function makeGrid(x,y) {
event.preventDefault();
if (document.getElementById('tbl') != null)
{
return;
}
else
{
var body = document.getElementById('pixelCanvas');
var tbl = document.createElement('table');
for(var i = 0; i < x; i++){
var tr = tbl.insertRow();
for(var j = 0; j<y; j++){
var td= tr.insertCell()
}
}
body.append(tbl);
paint()
}
}
HTML
<h2>Design Canvas</h2>
<table id="pixelCanvas">
</table>
The table gets created two times after I click submit two times
You should set the tbl's id to 'tbl' by tbl.id = 'tbl'.
You are doing the check on the id of the table but never assign one.
function makeGrid(x,y) {
event.preventDefault();
if (document.getElementById('tbl') != null) {
return;
} else {
var body = document.getElementById('pixelCanvas');
var tbl = document.createElement('table');
tbl.id = "tbl"; // Assign the id for the check
for(var i = 0; i < x; i++){
var tr = tbl.insertRow();
for(var j = 0; j<y; j++){
var td= tr.insertCell()
}
}
body.append(tbl);
paint();
}
};

Reorder CSV rows

I have this code which basically reads a CSV and should output a table where the CSV row content should be reordered!
Example :
fish;4;1;33
fish should be at 1 row column 4.
dog;5;2;66
dog should be at 2nd row column 5
The problem is that it doesn't print anything, neither at the console! Can you please show me where I am wrong? What modifications should I do?
My code:
function processFile() {
var fileSize = 0;
var theFile = document.getElementById("myFile").files[0];
if (theFile) {
var table = document.getElementById("myTable");
var headerLine = "";
var myReader = new FileReader();
myReader.onload = function(e) {
var content = myReader.result;
var lines = content.split("\r");
for (var i = 0; i <lines.length; i++)
{
document.write("<th>");
document.write(" ");
document.write("</th>");
}
for (var i = 0; i <lines.length; i++)
{
document.write("<tr>");
for (var j = 0; j <lines.length; j++)
{
document.write("<td>");
document.write(" ");
document.write("</td>");
}
document.write("</tr>");
}
function insertData(id, content) {
var dataRows = content.split("\r");
if (table) {
dataRows.forEach(function(s) {
var x = s.split(';');
table.rows[x[2]].cells[x[1]].textContent = x[0];
});
}
}
}
myReader.readAsText(theFile);
}
return false;
} //end
So, i did everything again for you with a big example.
I think you can handle it in your code, or take mine in the example.
Here are the main functions you can safely use in your case :
//for swapping values
function swap(arr, a, b){
var tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
return arr;
}
//for reorder lines a<=>b
function reorderLine(csvArray,a,b){
return swap(csvArray,a,b);
}
//for reorder one col values a<=>b
function reorderColumn(csvLine,a,b){
return swap(csvLine.split(";"),a,b).join(';');
}
// create a table with csv data
function csvArrayToTable(csvArray,selectorId){
var html = ["<table cellpadding='10' border='1'>"];
csvArray.map(function(lines){
html.push("<tr>");
var cols = lines.split(";");
html.push("<th>"+cols[0]+"</th>");
cols.shift();
cols.map(function(val){
html.push("<td>"+val+"</td>");
});
html.push("</tr>");
});
html.push("</table>");
document.getElementById(selectorId).innerHTML = html.join('');
}
And a working example you can use too, upload file is included (click on Run code snippet at the bottom of the post, and full page to test) :
//for swapping values
function swap(arr, a, b){
var tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
return arr;
}
//for reorder lines a<=>b
function reorderLine(csvArray,a,b){
console.log('reorderLine',csvArray,a,b);
return swap(csvArray,a,b);
}
//for reorder one col values a<=>b
function reorderColumn(csvLine,a,b){
console.log('reorderColumn',csvLine,a,b);
return swap(csvLine.split(";"),a,b).join(';');
}
// create a table with csv data
function csvArrayToTable(csvArray,selectorId){
var html = ["<table cellpadding='10' border='1'>"];
csvArray.map(function(lines){
html.push("<tr>");
var cols = lines.split(";");
html.push("<th>"+cols[0]+"</th>");
cols.shift();
cols.map(function(val){
html.push("<td>"+val+"</td>");
});
html.push("</tr>");
});
html.push("</table>");
document.getElementById(selectorId).innerHTML = html.join('');
}
// init element
var rawCsvFile = document.getElementById("csvInput");
var rawCsv = document.getElementById("rawCsv");
var reorderedRawCsv = document.getElementById("reorderedRawCsv");
var lines = document.getElementById("lines");
var lineA = document.getElementById("lineA");
var lineB = document.getElementById("lineB");
var colA = document.getElementById("colA");
var colB = document.getElementById("colB");
var apply = document.getElementById("apply");
var reset = document.getElementById("reset");
var rawCsvData, reorderCsvData;
// file uploaded
rawCsvFile.addEventListener("change", function() {
// reader
var reader = new FileReader();
// the file is loaded
reader.onload = function(e) {
// cancel if undefined
if(!reader.result || typeof reader.result != "string") return;
// Get result from new FileReader()
rawCsvData = reader.result.split(/[\r\n]+/g); // split lines
rawCsv.innerHTML = reader.result; // show in textarea
reorderedRawCsvData = rawCsvData; // clone data at start
function showCsvValueInForm(){
// empty fields
lines.innerHTML = "";
lineA.innerHTML = "";
lineB.innerHTML = "";
colA.innerHTML = "";
colB.innerHTML = "";
// Show in Raw CSV textarea
reorderedRawCsv.innerHTML = reorderedRawCsvData.join("\r\n");
// Add All option in On
var toAll = document.createElement('option');
toAll.value = "all";
toAll.innerHTML = "All";
lines.appendChild(toAll);
// handle line change
reorderedRawCsvData.map(function(val,i){
var lineOpt = document.createElement('option');
lineOpt.value = i;
lineOpt.innerHTML = i + " - " +(val.split(';'))[0];
// add options in line selects
lines.appendChild(lineOpt.cloneNode(!!1));
lineA.appendChild(lineOpt.cloneNode(!!1));
lineB.appendChild(lineOpt);
});
// handle col change
var nCol = rawCsvData[0].split(';');
nCol.map(function(val,i){
var colOpt = document.createElement('option');
colOpt.value = i;
colOpt.innerHTML = i;
// add options in col selects
colA.appendChild(colOpt.cloneNode(!!1));
colB.appendChild(colOpt);
});
// create table
csvArrayToTable(reorderedRawCsvData,"reorderedCsvTable");
}
// fill select, option and table with the reordered csv data
showCsvValueInForm();
// apply event, change the order
apply.addEventListener("click", function() {
// reordering line
var lineAOpt = lineA.options[lineA.selectedIndex].value;
var lineBOpt = lineB.options[lineB.selectedIndex].value;
if(lineAOpt !== lineBOpt) reorderedRawCsvData = reorderLine(reorderedRawCsvData,lineAOpt,lineBOpt);
// reordering col (all or only one)
var colAOpt = colA.options[colA.selectedIndex].value;
var colBOpt = colB.options[colB.selectedIndex].value;
if(colAOpt !== colBOpt)
if(lines.value == "all"){
reorderedRawCsvData = reorderedRawCsvData.map(function(val,i){
return reorderColumn(val,colAOpt,colBOpt);
});
}else{
reorderedRawCsvData[lines.value] = reorderColumn(reorderedRawCsvData[lines.value],colAOpt,colBOpt);
}
// fill again
showCsvValueInForm();
});
// reset the form with raw values
reset.addEventListener("click", function() {
if (confirm("Are you sure ?")) {
// reset
reorderedRawCsvData = rawCsvData;
// fill again
showCsvValueInForm();
}
});
}
// read the uploaded csv file as text
reader.readAsText(event.target.files[0], 'utf-8');
});
body { padding:10px; background:#eee; text-align: left; font-family: sans-serif; }
fieldset { width:80%; background:#fff; }
<html>
<head>
<title>CSV Reorder</title>
</head>
<body>
<h1>Reorder CSV</h1>
<fieldset>
<h3>Step 1 - Raw CSV</h3>
<small>Load a CSV file (not nested)</small>
<br />
<input type="file" id="csvInput">
<br />
<br />
<div>
<textarea id="rawCsv" placeholder="Waiting for a file..."></textarea>
</div>
</fieldset>
<br />
<fieldset>
<h3>Step 2 - Reordering Option</h3>
<small>Choose how to order the CSV data</small>
<br />
<table>
<tr>
<td>Line</td>
<td><select id="lineA"></select></td>
<td><=></td>
<td><select id="lineB"></select></td>
</tr>
<tr>
<td>Column</td>
<td><select id="colA"></select></td>
<td><=></td>
<td><select id="colB"></select></td>
<td>on</td>
<td><select id="lines"></select></td>
</tr>
<tr>
<td colspan="4"><button id="apply">Apply</button> <button id="reset">Reset</button></td>
</tr>
</table>
</fieldset>
<br />
<fieldset>
<h3>Step 3 - Reordered CSV</h3>
<small>Get the reordered values</small>
<br />
<div>
<textarea id="reorderedRawCsv" placeholder="Waiting for options..."></textarea>
</div>
<div>
<h3>Reordered CSV in a table</h3>
<div id="reorderedCsvTable">
<small>Waiting for a file..</small>
<br />
</div>
</div>
</fieldset>
</body>
</html>
Enjoy !

Reload popup with information

I have a table in my popup and I save the values entered by a user to localStorage. Here are the snippets.
popup.html
<table id="main_table">
</table>
<script src="popup.js"></script>
popup.js
function create_row() {
localStorage["last_session"] = true;
var table = document.getElementById("main_table");
var n = table.rows.length;
var m = table.rows[0].cells.length;
var row = table.insertRow(n);
if (!localStorage['use_storage']) {
if (n === 1) {
localStorage["cells"] = JSON.stringify([{}]);
}
else if (n > 1) {
var cells = JSON.parse(localStorage["cells"]);
cells.push({});
localStorage["cells"] = JSON.stringify(cells);
}
}
var cell = row.insertCell(0);
cell.innerHTML = n;
for (j=1; j<m; j++) {
create_cell(n-1, j, row);
}
return row
}
function create_cell(i, j, row){
var cell = row.insertCell(j);
if (j == 1) {
cell.innerHTML = "<input size=10>";
}
else {
cell.innerHTML = "<input size=4>";
}
cell.addEventListener("change", function () {
var cells = JSON.parse(localStorage["cells"]);
cells[i.toString()][j.toString()] = cell.childNodes[0].value;
localStorage["cells"] = JSON.stringify(cells);
})
}
document.getElementById('create_row').onclick = create_row;
// restore a table
if (localStorage["last_session"]) {
localStorage["use_storage"] = true;
try {
var cells = JSON.parse(localStorage["cells"]);
var n = cells.length;
var table = document.getElementById("main_table")
for (i=0; i<n; i++) {
var row = create_row(true);
var cell = cells[i]
for (var key in cell) {
if (cell.hasOwnProperty(key)) {
var col = parseInt(key);
var val = cell[key];
row.cells[col].childNodes[0].value = val;
}
}
}
} catch (e) {
console.log("Catched error");
console.log(e);
}
if (localStorage["results"]) {
show_results();
}
localStorage['use_storage'] = false;
}
In my browser it works as it is supposed, that is after refreshing a page popup.html I have the state where I left (number of rows and values are preserved). However, in my chrome extension, after clicking to any area and thus reloading the extension, I have the initial empty table.
How can I preserve the table in this particular case?

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