I already have add/delete rows dynamically in Javascript, there is no problem in adding rows, only having a problem with deleting rows.
For now, what I have made is when I want to delete a row it always deletes the last one, so I think I want if it only can be deleted the selected row, and I don't know how to modify the script to what I wanted be.
Here is the script:
var i=0;
function addRow()
{
i++;
m.r.value = i;
var tbl = document.getElementById('table');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
var cellRightSel1 = row.insertCell(1);
var sel = document.createElement('select');
sel.name = 'name' + iteration;
sel.setAttribute("onchange", "choosec(this);");
var item = new Option("","");
sel.options[sel.length] = item;
<?
while($data = mysql_fetch_array($result)){
?>
var item = new Option("<?=$data["Name"];?>","<?=$data["ID"];?>");
sel.options[sel.length] = item;
<? } ?>
cellRightSel1.appendChild(sel);
var cellRightSel2 = row.insertCell(2);
var sel = document.createElement('select');
sel.name = 'class' + iteration;
sel.setAttribute("onchange", "choosepoint(this);");
var item = new Option ("","");
sel.options[sel.length] = item;
<?
while($data = mysql_fetch_array($result_sub)){
?>
var item = new Option("<?=$data["Class"];?>","<?=$data["ID"];?>");
sel.options[sel.length] = item;
<? } ?>
cellRightSel2.appendChild(sel);
var cellRight = row.insertCell(3);
var div = document.createElement('div');
div.id = 'point' + iteration;
cellRight.appendChild(div);
}
function removeRow(){
var tbl = document.getElementById('table');
var lastRow = tbl.rows.length;
var rem = lastRow - 1;
if (lastRow > 2) tbl.deleteRow(rem);
}
Help is appreciated, thanks.
My solved problems:
function removeRow(t){
var i = t.parentNode.parentNode.rowIndex;
var tbl = document.getElementById('table');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
tbl.deleteRow(i);
}
try it like this
<tr onclick="removeRow(this);">...</tr>
then in javascript method
function removeRow(row){
var tbl = row.parentNode;
var index = row.parentNode.rowIndex;
if (index > 2) tbl.deleteRow(index);
}
I found one good example suitable your requirement. check here
This is the code that needs to be changed:
var rem = lastRow - 1;
Right now, that's always going to be the last row. You can build some logic around that to pass in an index, or hunt for a string, or whatever, but tbl.deleteRow() needs to delete at a particular index.
If you wanted to delete the 3rd row, for example:
var rem = 2; //zero-based index
Related
I am building a gradebook web app. I wanted the app to have the ability to calculate grades upon pushing the Final button. However, it's not working for some reason:
var myTable = document.getElementById("myTable");
var r = 0;//how many rows; row index
var c = 1;//how many columns
//make a table
//table must be able to add rows
//table cells should be editable
//save changes?
//
//make a table head row
//all table columns must have a table head
//**
// var firstRow= myTable.insertRow(0);
function addRow(){
//make a new row
var row = myTable.insertRow(r);
//use a while loop to keep creating row cells until you reach last column
var i = 0;
while(i<c){
var cell = row.insertCell(i);
cell.innerHTML ="Students[i]";
i++;
}
r++;
}
function addColumn(){
//make new column
//increment column
var tHead = document.createElement("th");
var allRows= document.getElementsByTagName("tr");//get all rows
//put tHead in first row
allRows[0].append(tHead);
var dateTable = document.createElement("input");
dateTable.type = "date";
tHead.appendChild(dateTable);
//tHead.innerHTML = (c*2);
//add a new cell for each row
var j =1;
while(j<allRows.length){
var row2 = allRows[j];
var cell2 = row2.insertCell(c);
cell2.innerHTML = j;
j++;
}
c++;
f++;
//if there already id a final row, delete it
}
function unEdit(){
//go through every cell
//save input value to a variable
//remove the input cell
var valArray =[];
document.querySelectorAll("td>input").forEach(input => {
var num = parseInt(input.value);
valArray.push(num);
input.remove();
});
//put input value into innerhtml of td
var i = 0;
document.querySelectorAll("td").forEach(td =>{
td.innerHTML=valArray[i];
i++;
});
}
function editTable(){
var allCells = document.getElementsByTagName("td");
for(var k=0; k<allCells.length; k++){
var oldText= allCells[k];
var input = document.createElement("input");
input.type ="number";
input.max = 100;
input.min = 0;
//before making all cells input, save previous innerhtml to var,
//make it into a num instead of a string, and put that value into input
var prev = allCells[k].innerHTML;
prev = parseInt(prev);
input.value = prev;
allCells[k].innerHTML = "";
allCells[k].appendChild(input);
input.onblur;
}
}
function deleteRow(){
document.getElementById("myTable").deleteRow(1);
r--;
}
function deleteColumn(){
//go through each row
//delete cell at each index
var everyRow = document.getElementsByTagName("tr");
for(var p=0; p<everyRow.length; p++){
everyRow[p].deleteCell(-1);
}
c--;
var finalButton = document.getElementById("final");
finalButton.enabled = true;
}
//final grade column
function finalRow(){
//make a <thead>
//make a new cell going down
var finalHead = document.createElement("th");
finalHead.innerHTML= "Final Grade";
var theseRows = document.getElementsByTagName("tr");
theseRows[0].append(finalHead);
for(var t =1; t<theseRows.length; t++){
//go through every cell in the row
//total up the numbers and put it in the final cell
var finalTotal=0;
for(var e =1; e< theseRows[t].length; e++){
var numero = theseRows[t][e].value;
numero = parseInt(numero);
console.log(numero);
finalTotal += numero;
}
//add up the innerhtmls and put it in finalCell
var finalCell = theseRows[t].insertCell(-1);
finalCell.innerHTML = finalTotal;
}
c++;
//disable final button
var finalButton = document.getElementById("final");
finalButton.disabled = true;
var days = document.getElementById("days");
days.disabled = true;
}
addRow();
addColumn();
//make a table head row at the top
//maybe add a print button?
//add a final grade column
//make it so that final row stays final when add new students and days
//do final funtion inside of unEdit() at the end?????
table,td,th{
border: 1px solid black;
border-collapse: collapse;
}
<table id = "myTable"></table>
</script>
<button onclick ="addRow()">Students</button>
<button onclick ="addColumn()" id ="days">Days</button>
<button onclick="editTable()">Edit</button>
<button onclick="unEdit()">Unedit</button>
<button onclick="deleteRow()">Delete Row</button>
<button onclick="deleteColumn()">Delete Column</button>
<button onclick ="finalRow()" id ="final">Final</button>
<button>Print</button>
In the finalRow() function, I can't figure out why the total I keep getting is always 0. Why doesn't it add up the value of the cells? I wanted it to go through every row, get the number values from each cell and total it up. It seems like the issue is with the "numero" variable, but I'm not sure what the issue is.
the first error is because you forgot to declare the variable f, you declared only the variables r and c above.
the second is in the function DeleteRow() there is an indexing error because it finds a negative value when deleting the last row. If you don't even want him to delete the last row, I suggest using a Try-Catch to deal with this error.
I would like to open a new page when I tap a cell (TR) in Javascript. I've searched a lot of tutorials online but it doesn't work as well. I hope that someone could help me. Thanks.
Here is my code:
function generateTableBirre()
{
//Build an array containing Customer records.
var birre = ["Heineken", "Nastro Azzurro", "Bjørne", "Leffe", "Peroni"];
var price = ["3,00$", "1,00$", "3,00$", "2,00$", "4,50$"];
//Create a HTML Table element.
var table = document.createElement("Table");
table.border = "1";
table.className = "Birre";
table.cellSpacing = 20;
//Add the data rows.
for (var i = 0; i < birre.length; i++) {
row = table.insertRow(-1);
var cell = row.insertCell(-1);
var generalDiv = document.createElement("div");
generalDiv.className = "General-Div";
// Create an a tag
var a = document.createElement('a');
a.href = "Antipasti.html";
a.appendChild(cell);
cell.appendChild(a);
var div = document.createElement("div");
div.id = "div-nome-prezzo-birre";
var nameprezzo = document.createElement("p");
nameprezzo.innerHTML = birre[i] + ' - ' + price[i];
nameprezzo.id = "nome-prezzo-birre";
div.appendChild(nameprezzo);
var image = document.createElement("img");
image.src = "https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png"
image.id = "image-bibite";
generalDiv.appendChild(div);
generalDiv.appendChild(image);
cell.appendChild(generalDiv);
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
If you would like to show the table, here is the image:
In the Javascript below the table is created with 2 cells per row. In the first cell you'll find a div with a text paragraph. In the second cell you'll find a div with anchor and image.
Important: an id must be unique so I had to remove lines where duplicate id's were created. If you want to use extra selectors then you can use classList.add("...")
In the css you can style the image width, font, color, etc. For example #dvTable img { max-width: 250px; height: auto; border: 0; }
function generateTableBirre() {
// array containing records
var birre = ["Heineken", "Nastro Azzurro", "Bjørne", "Leffe", "Peroni"];
var price = ["3,00$", "1,00$", "3,00$", "2,00$", "4,50$"];
// create table
var table = document.createElement('table');
table.classList.add("Birre");
table.setAttribute('border', '1');
table.setAttribute('cellspacing', '20');
// loop through the array and create rows
for (var i = 0; i < birre.length; i++) {
var row = document.createElement('tr');
// loop from 0 to 1 to create two cells on each row
for (var j = 0; j < 2; j++) {
var cell = document.createElement('td');
// give each cell a inner div
var div = document.createElement("div");
div.classList.add("General-Div");
cell.appendChild(div);
// different content in cell 0 and cell 1
if (j == 0) {
// cell 0 contains paragraph
var par = document.createElement("p");
par.innerHTML = birre[i] + ' - ' + price[i];
div.appendChild(par);
} else {
// cell 1 contains image in an anchor
var anch = document.createElement('a');
anch.setAttribute('href', 'Antipasti.html');
div.appendChild(anch);
var img = document.createElement("img");
img.setAttribute('src', 'https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png');
anch.appendChild(img);
}
row.appendChild(cell);
}
table.appendChild(row);
}
// append table in id=dvTable
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
generateTableBirre();
<div id="dvTable">
</div>
try this,
function generateTableBirre() {
//Build an array containing Customer records.
var birre = ["Heineken", "Nastro Azzurro", "Bjørne", "Leffe", "Peroni"];
var price = ["3,00$", "1,00$", "3,00$", "2,00$", "4,50$"];
//Create a HTML Table element.
var table = document.createElement("table");
table.border = "1";
table.className = "Birre";
table.cellSpacing = 20;
//Add the data rows.
for (var i = 0; i < birre.length; i++) {
//var row = table.insertRow(-1);
//var cell = row.insertCell(-1);
var row = document.createElement("tr");
table.appendChild(row);
var cell = document.createElement("td");
var generalDiv = document.createElement("div");
generalDiv.className = "General-Div";
// Create an a tag
var a = document.createElement('a');
a.href = "Antipasti.html";
a.appendChild(cell);
row.appendChild(a);
var div = document.createElement("div");
div.id = "div-nome-prezzo-birre";
var nameprezzo = document.createElement("p");
nameprezzo.innerHTML = birre[i] + ' - ' + price[i];
nameprezzo.id = "nome-prezzo-birre";
div.appendChild(nameprezzo);
var image = document.createElement("img");
image.src = "https://www.talkwalker.com/images/2020/blog-headers/image-analysis.png"
image.id = "image-bibite";
generalDiv.appendChild(div);
generalDiv.appendChild(image);
cell.appendChild(generalDiv);
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
EDIT: With significant help from others, I was able to work up a solution.
I'm taking data from a Google Spreadsheet and then attempting to render it as an HTML table in a WebApp.
I'd like the data to show up like
<tr>
<td>
<td>
<td>
exactly how it looks in a spreadsheet, with each value in a separate cell.
Big picture, I'd like to be able to do different things to each <td>, so I want to make sure I structure the data in a usable way.
Code.GS
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
function webAppTest() {
getTeamArray();
}
function getTeamArray() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName('Sheet1');
var range = sheet.getRange('A2:H1000');
var values = range.getValues();
//Logger.log(values);
var teamsArray = [];
for (var i = 0; i < values.length; ++i) {
var column = values[i];
var colA = column[0];
var colB = column[1];
var colC = column[2];
var colD = column[3];
var colE = column[4];
var colF = column[5];
var colG = column[6];
var colH = column[7];
if (colA != '') {
teamsArray.push(values[i][0]);
teamsArray.push(values[i][3]);
teamsArray.push(values[i][4]);
}
}
var array2 = [];
while(teamsArray.length) array2.push(teamsArray.splice(0,3));
var lengthDivName2 = array2.length;
var widthDivName2 = array2[0].length;
//Logger.log(teamsArray);
Logger.log(array2);
//return teamsArray;
return array2;
}
Index.HTML Function
function buildOptionsList(teamsArray) {
var div = document.getElementById('myList');
for (var i = 0; i < teamsArray.length; i++) {
var tr = document.createElement('tr');
var td = document.createElement('td');
var cLass = td.setAttribute('class','ui-state-default');
var iD = td.setAttribute('id',teamsArray[i]);
td.appendChild(document.createTextNode(teamsArray[i]));
div.appendChild(tr);
div.appendChild(td);
}
}
</script>
</head>
<body>
<div id="myList" class="connectedSortable">MY LIST</div>
</body>
</html>
ATTEMPT 1
ATTEMPT 2
I tried to change the array creation in code.gs which got all the correct data in the <tr> but didn't split into <td>s
I am not sure I understood the way you receive the data, but if teamsArray contain information about one line the solution would be something like this:
function buildOptionsList(teamsArray) {
var div = document.getElementById('myList');
var tr = document.createElement('tr');
for (var i = 0; i < teamsArray.length; i++) {
var td = document.createElement('td');
var cLass = td.setAttribute('class','ui-state-default');
var iD = td.setAttribute('id',teamsArray[i]);
td.appendChild(document.createTextNode(teamsArray[i]));
tr.appendChild(td);
}
div.appendChild(tr);
}
Use Array#map, Array#reduce, and Array#join to surround the elements of the inner array with the required HTML tags and then condense to a single string. Currently you have an implicit Array#toString call which creates a comma-separated string of the inner array's elements (the inner array is at teamData[i]), and thus you only have a single cell in your previous attempts' output.
This simple function assumes you aren't applying any column- or row-specific styles or attributes, so it can simply treat every <td> element equivalently. If you have symmetric styling to apply, you would want to process the headers/row variables with .map first (since you can then use the elements' indices) and then .join("") instead of just .join using the tag delimiters.
function getTableHTMLFrom(array, hasHeaders) {
if (!array || !array.length || !array[0].length)
return "";
const headerString = (hasHeaders ?
"<tr><th>" + array.shift().join("</th><th>") + "</th></tr>"
: "");
const tdTag = "<td class=\"ui-state-default\">";
const bodyString = array.reduce(function (s, row) {
s += "<tr>" + tdTag + row.join("</td>" + tdTag) + "</td></tr>";
return s;
}, "");
return "<table>" + headerString + bodyString + "</table>";
}
I found a solution (applied to Index.HTML) that worked based on THIS.
function buildOptionsList(array2) {
var table = document.createElement('table');
var tableBody = document.createElement('tbody');
array2.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
var cLass = td.setAttribute('class','ui-state-default');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.body.appendChild(table);
}
buildOptionsList(array2);
For some reason I am unable to re-enable a button and go through all of the columns I have in a table with the same button. Can I create multiple onclick events for the button? The HTML itself is really just a button within a table.
function focaccia(x){
var table = document.getElementById("orderTable");
var row = table.insertRow(0);
var rem = document.createElement("button");
var name = document.createTextNode("Remove");
rem.appendChild(name);
rem.onclick = function(){
x.disabled = false;
document.getElementById("orderTable").deleteRow(this);
var table = document.getElementById("orderTable");
var amount = 0;
var tot;
for(var x = 0; x < table.rows.length; x++){
amount = amount + parseInt(table.rows[x].cells[1].children[0].value);
}
tot = amount * 9;
document.getTotal.total.value = tot;
}
var num = document.createElement("input");
num.size = 2;
num.onchange = function(){
var table = document.getElementById("orderTable");
var amount = 0;
var tot;
for(var x = 0; x < table.rows.length; x++){
amount = amount + parseInt(table.rows[x].cells[1].children[0].value);
}
tot = amount * 9;
document.getTotal.total.value = tot;
}
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "Focaccia";
cell2.appendChild(num);
cell3.appendChild(rem);
x.disabled = true;
num.value = 1;
total = total + 9;
document.getTotal.total.value = total;
}
Yes, use addEventListener.
Instead of target.onclick=clickHandlerFunction;, use target.addEventListener('click', clickHandlerFunction);'
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener
Note: The syntax for adding events using old Internet Explorer is different (target.attachEvent('onclick',handler)). If you need compatibility with old browsers, you can use both syntaxes, use jQuery's click or on functions or gator.js.
I want to delete a row from a table created by JavaScript. i tried the code from different post on this page but doesn't solve it.
function value_pass()
{
var Delete = document.createElement("input");
Delete.type="button";
Delete.name = "del"
Delete.value = "Delete";
Delete.onclick = function(o)
{
var r = o.parentElement.parentElement;
document.getElementById("table").deleteRow(r.rowIndex);
}
var order_no = document.getElementById("Order_no");
var quantity = document.getElementById("quantity");
var type = document.getElementById("Recipe");
var recipe = type.options[type.selectedIndex].text;
var body1 = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute("id","table");
var tblbody = document.createElement("tbody");
tbl.setAttribute("border","2");
var col = document.createElement("td");
for (var j = 0; j < 1; j++)
{
var rows = document.createElement("tr");
for (var i = 0; i < 4; i++)
{
var col1 = document.createElement("td");
var col2 = document.createElement("td");
var col3 = document.createElement("td");
var col4 = document.createElement("td");
var col5 = document.createElement("td");
var col1text = document.createTextNode(order_no.value);
var col2text = document.createTextNode(recipe);
var col3text = document.createTextNode(quantity.value);
var col4text = document.createTextNode();
//also want to put checked values in table row
}
col1.setAttribute("width","150");
col2.setAttribute("width","150");
col3.setAttribute("width","150");
col4.setAttribute("width","150");
col1.appendChild(col1text);
col2.appendChild(col2text);
col3.appendChild(col3text);
col4.appendChild(col4text);
col5.appendChild(Delete);
rows.appendChild(col1);
rows.appendChild(col2);
rows.appendChild(col3);
rows.appendChild(col4);
rows.appendChild(col5);
tblbody.appendChild(rows);
} tbl.appendChild(tblbody);
body1.appendChild(tbl);
}
The function will be called by a button in HTML
its an order form that
and also want to know about the checked values of checkbox to put in the table row.
You can use :
document.getElementById("myTable").deleteRow(0); //Where 0 is your row.
Explained : http://www.w3schools.com/jsref/met_table_deleterow.asp
Edit:
To delete the current row, set this on your button: onclick="deleteRow(this), with the following code in that function:
function deleteRow(t)
{
var row = t.parentNode.parentNode;
document.getElementById("myTable").deleteRow(row.rowIndex);
console.log(row);
}