i've been looking a while if somebody had a similar question, and there are a few, but not with the solution i need. their increments work perfectly fine but when they have a some rows like this
id
1 hello
2 hello
3 hello
4 hello
but when they delete row 3, row 4 becomes 3. I want it just like php where 4 stays 4 and doesn't become 3 so the next time you would add a row it would look like
id
1 hello
2 hello
4 hello
5 hello
see the following code for yourself; I can't figure it out
<table id="myTable">
<thead>
<tr>
<th>id</th>
<th>titel</th>
<th>beschrijving</th>
<th>deadline</th>
<th>delete task</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div class="forms flex flex-around">
<form >
<h2>Add Tasks</h2>
titel: <input type="text" name="titel" id="send"><br />
beschrijving: <input type="text" id="send" name="beschrijving"><br />
deadline: <input type="date" id="send" name="deadline"><br />
<!-- <input type="submit" value="Add" name="type" class="center" onclick="myFunction()"> -->
<button type="button" value="Add" id="handler" class="center button-add" onclick="addRow(); ">add task</button>
</form>
</div>
$(document).ready(function() {
buildTable();
});
function buildTable() {
const retrievedTaskObject = localStorage.getItem("table");
const parsedObject = JSON.parse(retrievedTaskObject);
for (i = 0; i < parsedObject.length; i++) {
addRow(parsedObject[i])
}
}
function addRow(rowData = false) {
var table = document.getElementById("myTable").getElementsByTagName('tbody')[0];
var row = table.insertRow(table.rows.length);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
if (!rowData) {
cell2.innerHTML = '<td>' + document.querySelector('[name="titel"]').value; + '</td>';
cell3.innerHTML = document.querySelector('[name="beschrijving"]').value;
cell4.innerHTML = document.querySelector('[name="deadline"]').value;
} else {
cell2.innerHTML = '<td>' + rowData.title + '</td>';
cell3.innerHTML = rowData.description;
cell4.innerHTML = rowData.deadline;
}
cell5.innerHTML = '<button class="button-add last-row" type="button" onClick="deleteRow()" >' +
'delete</button>';
getAndSaveTableValues();
}
function getTblValues(tableName = false) {
if (!tableName) {
console.log('Please enter a tableName, function won\'t work without it');
return;
}
const dataArray = new Array();
$(`${tableName} tbody tr`).each(function(rowIndex, tr) {
dataArray[rowIndex] = {
"id": rowIndex,
"title": $(tr).find('td:eq(1)').text(),
"description": $(tr).find('td:eq(2)').text(),
"deadline": $(tr).find('td:eq(3)').text()
}
});
return dataArray;
}
function deleteRow() {
var td = event.target.parentNode;
var tr = td.parentNode;
tr.parentNode.removeChild(tr);
getAndSaveTableValues();
};
as you can see I have pretty much everything set, but because my messyness and few months of coding I completely lost track and don't know how to fix the increment I've tried many things but ended up breaking it fully,
Any help is welcome not only the solution but if you see something that could be smarter coded let me know
I do not fully know how to fix this problem, but have you tried to replace the value with null instaed of .removeChild(tr)?
Related
I am obviously very new to JS. I need to solve a problem where i can't change the HTML and CSS-file. From the HTML-file I am supposed to:
add a column with the header "Sum". (Already did that)
add a row att the bottom with the div id "sumrow". (Did that as well)
add a button at the end. (Did that)
add the total from columns "Price and Amount" into column "Sum" when button is clicked
(This where I am lost)
And like I said I can't change anything in HTML and CSS-files.
// Create a newelement and store it in a variable
var newEl = document.createElement('th');
//Create a text node and store it in a variable
var newText = document.createTextNode('Summa');
//Attach the newtext node to the newelement
newEl.appendChild(newText);
//Find the position where the new element should be added
var position = document.getElementsByTagName('tr')[0];
//Insert the newelement into its position
position.appendChild(newEl);
// Find a <table> element with id="myTable":
var table = document.getElementById("pricetable");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(-1);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
// Add some text to the new cells:
cell1.innerHTML = "";
cell2.innerHTML = "";
cell3.innerHTML = "";
cell4.innerHTML = sumVal;
cell5.innerHTML = "";
cell6.innerHTML = "";
//Puts divid sumrow
row.setAttribute("id", "sumrow");
var table = document.getElementById("pricetable"), sumVal = 0;
for(var i = 1; i < table.rows.length; i++)
{
sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
}
//Creates button
var button = document.createElement("button");
button.innerHTML = "Beräkna pris";
// 2. Append somewhere
var body = document.getElementsByTagName("tbody")[0];
body.appendChild(button);
button.addEventListener("click", medelVarde, true);
button.addEventListener("click", raknaUtMedelvarde, true);
button.setAttribute("class", "btn-primary");
function medelVarde(celler){
var summa = 0;
for(var i = 3; i < celler.length -1; i++){ //Räknar igenom från cell nr 4
var nuvarandeVarde = celler[i].firstChild.nodeValue;
summa = summa + parseInt(nuvarandeVarde);
}
var medel = summa / 1;
return medel;
}
function raknaUtMedelvarde(){
var tabell = document.getElementById("pricetable");
var rader = tabell.getElementsByTagName("tr");
for(var i = 1; i < rader.length; i++){
var tabellceller = rader[i].getElementsByTagName("td"); //Pekar på de td-element som vi har hämtat
var medel = medelVarde(tabellceller);
var medeltext = document.createTextNode(medel);
var medelelement = tabellceller[tabellceller.length - 1];
var row2 = table.insertRow(-1);
medelelement.appendChild(medeltext.cloneNode(true));
.table {
background: white;
}
tr#sumrow {
background-color: #cce4ff;
}
tr#sumrow td:first-child::after{
content: "\a0";
}
<!DOCTYPE html>
<html lang="sv">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Handling calculations and tables</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="style/style.css" />
</head>
<body>
<div class="container">
<div id="header" class="text-center px-3 py-3 pt-md-5 pb-md-4 mx-auto">
<h1 class="display-4">Home Electronics</h1>
<p class="lead">Excellent prices on our hone electronics</p>
</div>
<div id="content">
<table id="pricetable" class="table table-hover">
<thead class="thead-dark">
<tr>
<th>Articlenr</th>
<th>Producttype</th>
<th>Brand</th>
<th>Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>23456789</td>
<td>Telephone</td>
<td>Apple</td>
<td>6500</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>22256289</td>
<td>Telephone</td>
<td>Samsung</td>
<td>6200</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>24444343</td>
<td>Telephone</td>
<td>Huawei</td>
<td>4200</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>19856639</td>
<td>Tablet</td>
<td>Apple</td>
<td>4000</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>39856639</td>
<td>Tablet</td>
<td>Samsung</td>
<td>2800</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
<tr>
<td>12349862</td>
<td>Tablet</td>
<td>Huawei</td>
<td>3500</td>
<td>
<input type="text" size="3" value="1" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- add this script as snippet in this question -->
<!-- <script src="scripts/calculate.js"></script> -->
</body>
</html>
Or code is available on https://jsfiddle.net/cmyr2fp6/
button.addEventListener("click", medelVarde, true);
button.addEventListener("click", raknaUtMedelvarde, true);
For the button click event listener, you don't have to add the medelVarde function.
Also, speaking of that function, I'm not really sure what's happening there. Are you trying to multiply the price and the amount? If so, you can just get the price cell's text and multiply it by the amount input's value (converting to Number the values before multiplying).
const [,,, priceCell, amountCell, sumCell] = row.querySelectorAll('td');
const price = Number(priceCell.innerText);
const amount = Number(amountCell.querySelector('input').value);
const sum = price * amount;
The [,,, priceCell, amountCell, sumCell] is just a short-hand for getting the cells you want from the row (destructuring assignment. querySelectorAll returns a NodeList wherein you can get the element by index.
function setUp() {
// Set up table.
const table = document.getElementById('pricetable');
const headerRow = table.querySelector('thead tr');
const sumHeader = headerRow.insertCell();
const tbody = table.querySelector('tbody');
const sumTotalRow = tbody.insertRow();
const sumTotalCell = sumTotalRow.insertCell();
sumHeader.innerText = 'Summa';
sumTotalCell.colSpan = '5';
sumTotalCell.innerText = 'Total';
tbody.querySelectorAll('tr').forEach(row => row.insertCell());
// Set up button.
const btn = document.createElement('button');
btn.innerText = 'Beräkna pris';
btn.addEventListener('click', () => {
let total = 0;
tbody.querySelectorAll('tr').forEach((row, i, arr) => {
if (i < arr.length - 1) {
const [,,, priceCell, amountCell, sumCell] = row.querySelectorAll('td');
const price = Number(priceCell.innerText);
const amount = Number(amountCell.querySelector('input').value);
const sum = price * amount;
sumCell.innerText = sum;
total += sum;
} else {
const totalCell = row.querySelector('td:last-child');
totalCell.innerText = total;
}
});
});
document.body.appendChild(btn);
}
setUp();
Hey ZioPaperone welcome to the JS World :-)
First of all I would recommend to wrap you logic into functions, eg
appendRow() {
//put append row logic here
}
Now let's move on to your question, appending a column is a bit more of a trick then appending a row. You might noticed already that the DOM-Structure is a bit more complex. So for a row you could you correctly has added a node to your tbody.
For a column we need to learn how to create a cell and how we add an entry to the thead. We will use the insertCell() method to insert cells, for thead cells that won't work, so we need to add the th with createElement() and append it with appendChild()
function appendColumn() {
// insertCell doesn't work for <th>-Nodes :-(
var tableHeadRef = document.getElementById('pricetable').tHead; // table reference
var newTh = document.createElement('th');
tableHeadRef.rows[0].appendChild(newTh); // inser new th in node in the first row of thead
newTh.innerHTML = 'thead title';
// open loop for each row in tbody and append cell at the end
var tableBodyRef = document.getElementById('pricetable').tBodies[0];
for (var i = 0; i < tableBodyRef.rows.length; i++) {
var newCell = tableBodyRef.rows[i].insertCell(-1);
newCell.innerHTML = 'cell text'
}
}
EDIT:
To sum up values in col u can use the same approach. I broke down the nodes for better understanding. You also might want to add a check if your table data contains a number with isNaN().
function sumColumn(tableId, columnIndex) {
var tableBodyRef = document.getElementById(tableId).tBodies[0];
var sum = 0; // Initialize sum counter with 0
for (var i = 0; i < tableBodyRef.rows.length; i++) {
var currentRow = tableBodyRef.rows[i]; //access current row
var currentCell = currentRow.cells[columnIndex]; // look for the right column
var currentData = currentCell.innerHTML; // grab cells content
var sum += parseFloat(currentData); // parse content and add to sum
}
return sum;
}
Hi i'm a beginner and I'm trying to do a simple CRUD Car apps but i cannot delete row with my function deleteRow().
I've create a function call deleteRow i add a checkbox in every row with the createElement method and i'm setting the Id attribute using the setAttribute() method.In my function i'm trying to get to the checkbox to see if its checked and if so using the deleteRow method to delete the row.
function addRow() {
/* check if its empty */
var brandValue = document.getElementById("brand").value;
var modelValue = document.getElementById("model").value;
if (brandValue == "" || modelValue == "") {
return alert("Make sure you enter a brand and a model!")
}
/* Add a row */
"use strict";
var table = document.getElementById("table");
var row = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var td3 = document.createElement("INPUT");
td3.setAttribute("type", "checkbox");
td3.setAttribute("id", "cb");
td1.innerHTML = document.getElementById("brand").value;
td2.innerHTML = document.getElementById("model").value;
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
table.children[0].appendChild(row);
document.getElementById('brand').value = "";
document.getElementById('model').value = "";
}
var temp = 1;
function deleteRow() {
for (var j = temp - 2; j >= 0; j--) {
if (document.table.cb[j].checked) {
document.getElementById("table").deleteRow(j + 1);
}
}
}
<input type="text" id="brand" placeholder="Add a brand">
<input type="text" id="model" placeholder="Add a Model">
<button type="button" onClick="addRow()" id="add">Update</button>
<button type="button" onClick="deleteRow()" id="delete">Delete</button>
<table id="table">
<div class="tableDiv">
<tr>
<th>Brands</th>
<th>Models</th>
<th>Select</th>
</tr>
</div>
</table>
Right now nothing happen when i'm trying to delete and i have nothing in the browser console.
Thanks for your help.
Try this:
const $brand = document.getElementById("brand")
const $model = document.getElementById("model")
const $table = document.getElementById("table")
function addRow() {
/* check if its empty */
if ($brand.value == "" || $model.value == "") {
return alert("Make sure you enter a brand and a model!")
}
let $row = document.createElement("tr");
let $td1 = document.createElement("td");
let $td2 = document.createElement("td");
let $td3 = document.createElement("input");
$td3.setAttribute("type", "checkbox");
$td1.innerHTML = $brand.value;
$td2.innerHTML = $model.value;
$row.appendChild($td1);
$row.appendChild($td2);
$row.appendChild($td3);
$table.children[0].appendChild($row);
$brand.value = "";
$model.value = "";
}
function deleteRow() {
let checkboxs = $table.querySelectorAll("input[type='checkbox']:checked")
checkboxs.forEach(checkbox => checkbox.parentElement.remove())
}
<input type="text" id="brand" placeholder="Add a brand"></input>
<input type="text" id="model" placeholder="Add a Model"></input>
<button type="button" onClick="addRow()" id="add">Update</button>
<button type="button" onClick="deleteRow()" id="delete">Delete</button>
</div>
<table id="table">
<div class="tableDiv" <tr>
<th>Brands</th>
<th>Models</th>
<th>Select</th>
</tr>
</div>
</table>
for (var j = temp - 2; j >= 0; j--) { this loop never starts due to temp being 1.
1 - 2 = -1 so the loop condition (j >= 0) is never true.
Your main mistake is that you don't need to iterate anything, you can select the checked elements directly.
Try using document.querySelector("#table input[type='checkbox']:checked")
Another thing is that now you are assigning the same id to multiple elements. This should not be done, it can lead to unexpected behavior. Consider using class or custom attribute instead
let checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
checkboxes.forEach(checkbox => checkbox.parentElement.parentElement.remove());
I can't sum the subtotals of an HTML column table using javascript. I need to sum the 5th column and put the result in a textbox so the costumer can see the totals of his bill. The thing is, I can't use database because it is a table that doesn't INSERT the value in the database until I hit the final button. Any help would be appreciated. Thanks a lot
var arr2 = "";
$('#añadir').click(function() {
var table = document.getElementById("tablaC");
var id_pla = document.getElementById("plato_id").value;
var pla = document.getElementById("plato_nombre").value;
var cantidad = document.getElementById("cantidad").value;
var punitario = document.getElementById("plato_precio").value;
var subtotal = (cantidad * punitario)
if (id_pla != "" && cantidad != "") {
var row = table.insertRow(cant);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
var cell5 = row.insertCell(5);
cell0.innerHTML = cant;
cell1.innerHTML = id_pla;
cell2.innerHTML = pla;
cell3.innerHTML = cantidad;
cell4.innerHTML = punitario;
cell5.innerHTML = subtotal;
cant++;
arr2 += id_pla + "," + cantidad + ","
$('#arr').val(arr2);
}
validar();
});
This is the HTML code
<table id="tablaC" class="table table-hover">
<thead>
<tr>
<th>ID Pedido</th>
<th>ID Plato</th>
<th>Plato</th>
<th>Cantidad</th>
<th>Precio Unitario</th>
<th>Subtotal</th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
<input id="arr" name="arr" value="" />
<br>
<br/>
<input class="btn btn-info" type="submit" value="Crear Registro" id="registro">
</form>
<p></p>
I notice several issues in your files codes, you should fix them in order to make this work:
1)
To compare with "" You should use strict equality "!==" instead of "!="
if (id_pla !== "" && cantidad !== "") {
instead of:
if (id_pla != "" && cantidad != "") {
2) "$" is not defined as a variable, unless you refer to jQuery.
/*here*/ $('#añadir').click(function() {
3) Ids missing in your HTML code:
Here you are saying:
var table = document.getElementById("tablaC");
var id_pla = document.getElementById("plato_id").value;
var pla = document.getElementById("plato_nombre").value;
var cantidad = document.getElementById("cantidad").value;
var punitario = document.getElementById("plato_precio").value;
But you are not giving any id to this elements on your html. It should be like this:
<th>ID Pedido</th>
<th id="plato_id">ID Plato</th>
<th id="plato_nombre">Plato</th>
<th id="cantidad">Cantidad</th>
<th id="plato_precio">Precio Unitario</th>
<th>Subtotal</th>
Hello I'm fairly new here so please correct me if I make any formatting or question errors!
I am attempting to create a simple shopping basket file and need some help getting the quantity of items within the basket to change. At the moment I can create a button that adds a new row to a table and fills it, I am just having a shortfall at getting the function to check if the item is already in the table and only update the quantity cell if it is. I am useless with IF statements, so any help would be more than appreciated!
<!DOCTYPE html>
<html>
<head>
<script>
function additem1() {
var table = document.getElementById("basket");
var row1 = table.insertRow(1);
var cell1 = row1.insertCell(0);
var cell2 = row1.insertCell(1);
var cell3 = row1.insertCell(2);
var cell4 = row1.insertCell(3);
var cell5 = row1.insertCell(4);
var cell6 = row1.insertCell(5);
cell1.innerHTML = "Shorts (f)";
cell2.innerHTML = "Stone Wash";
cell3.innerHTML = "1";
cell4.innerHTML = "";
cell5.innerHTML = "";
cell6.innerHTML = "";
;
}
</script>
<style>
table, td {
border: 1px solid black;
}
</style>
</head>
<body>
<h2> List of Items </h2>
<table border="1">
<tr bgcolor="#9acd32">
<th> Product </th>
<th> Description </th>
<th> Quantity </th>
<th> Price </th>
<tr>
<td> Shorts (F) </td>
<td> Stone wash Denim shorts </td>
<td> 20 </td>
<td> 25.90 </td>
<td> <button onclick= "additem1()"> Add Item To Basket </button> </td>
</table>
<table id="basket" border = "1">
<tr bgcolor="#9acd32">
<th> Product </th>
<th> Description </th>
<th> Quantity </th>
<th> Price </th>
<th colspan="2"> Add / Remove items </th>
</tr>
</table>
as you can see the first table holds the item information, and the second table holds the basket information.
Please consider to go deep on js coding; you can consider to check if the element already exist, then if so increment the quantity.
I made your code a little more generic, but for a working basket there is more to do, that's your job.
Code:
function additem1(e) {
var oRow = e.parentNode.parentNode
var prod = oRow.cells[0].innerHTML;
var des = oRow.cells[1].innerHTML;
var table = document.getElementById("basket");
var row1 = GetCellValues(prod);
if (typeof row1 === 'undefined') {
row1 = table.insertRow(1);
var cell1 = row1.insertCell(0);
var cell2 = row1.insertCell(1);
var cell3 = row1.insertCell(2);
var cell4 = row1.insertCell(3);
var cell5 = row1.insertCell(4);
var cell6 = row1.insertCell(5);
cell1.innerHTML = prod;
cell2.innerHTML = des;
cell3.innerHTML = "1";
cell4.innerHTML = "";
cell5.innerHTML = "";
cell6.innerHTML = "";;
} else {
row1.cells[2].innerHTML = parseInt(row1.cells[2].innerHTML) + 1
}
}
function GetCellValues(prod) {
var table = document.getElementById('basket');
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
if (table.rows[r].cells[c].innerHTML == prod) return table.rows[r];
}
}
return
}
Demo: http://jsfiddle.net/85o9yz02/
This is my first question on this awesome community.
I am using this javascript code to build a dynamic table:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
element2.onkeypress = "this.style.width = ((this.value.length + 1) * 8) + 'px'";
cell2.appendChild(element2);
}
And following html code to print it:
<table id="dataTable" style="width: 300px;" border="0">
<tr>
<td ><input type="checkbox" name="chk" /></td>
<td <input id="txt" type="text" onkeypress="this.style.width = ((this.value.length + 1) * 8) + 'px';"> </td>
</tr>
</table>
My problem is that- I want my text input field to be dynamically expending, but due to using 'document.createElement("input");' in the Javascript, only the first text input field expends dynamically rest
You can define your expanding function and reuse it later, like this:
expandTextBox = function (tb) {
tb.style.width = ((tb.value.length + 1) * 8) + 'px';
}
And when you create element:
var element2 = document.createElement("input");
element2.onkeypress = function() { expandTextBox(element2); };
And in html:
<input id="txt" type="text" onkeypress="expandTextBox(this)">
See the Fiddle
When add events to dynamically created elements in javascript, you must define the event code as a function not as a string!
So, modify your addRow function to this:
...
element2.onkeypress = function(){this.style.width = ((this.value.length+1)*8)+'px'};