Recalculate total when table row is deleted - javascript

Here is the fiddle. What I want is recalculate the total when I delete a row. I tried this, but it doesn't work:
tot -= parseInt(table.rows[i].cells[1].innerHTML)
table.deleteRow(i);
rowCount--;
i--;
Here is my code:
<div class="lorr">
<table id="myTable" border="1">
</table>
<br />
</div>
<button id="deletes">Remove Checked</button>
<button type="button" onclick="displayResult()">Insert new row</button>
<div id="total">
</div>
<script type="text/javascript">
function displayResult()
{
var swap = '<input type="checkbox" class="escondeyou">';
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = swap+"NEW CELL1ffffffffffffffffff ui7iytuiui riuiui ri";
cell2.innerHTML = "600";
cell2.style.fontWeight="bold";
cell2.style.wordBreak="keep-all";
var tot = "RD$"+document.getElementById("total").innerHTML;
// ******************** Important part ******************************
var tot=0;
for(var i=0;i<=rowCount;i++){
tot += parseInt(table.rows[i].cells[1].innerHTML);
}
document.getElementById("total").innerHTML=tot;
};
</script>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
Here is working: http://jsfiddle.net/joansuriel/QmHdL/50/

Here is what your click handler should do without changing too much your code. Note that you can reuse the calcTotal but be carefoul, I loop until i < table.rows.length
$('#deletes').click(function(){
$("table input[type='checkbox']:checked").parent().parent().remove();
calcTotal(document.getElementById("myTable"), document.getElementById("total"));
});
function calcTotal(table, total){
var tot = 0;
for(var i=0;i<table.rows.length;i++){
tot += parseInt(table.rows[i].cells[1].innerHTML);
}
total.innerHTML=tot;
}

So you have a delete method, just do something with it.
Your code:
$('#deletes').click(function(){
$("table input[type='checkbox']:checked").parent().parent().remove();
});
Change to:
$('#deletes').click(function(){
$("table input[type='checkbox']:checked").parent().parent().remove();
var $table = document.getElementById("myTable");
var total = 0;
for (var i=0; i < $table.rows.length; i++) {
var currentRow = $table.rows[i];
total = total + parseInt(currentRow.cells[currentRow.cells.length - 1].innerHTML);
}
document.getElementById("total").innerHTML = total.toString();
});
Comment me if you have any question.

Related

Unable to generate table after clearing table

I'm working on a project but am stuck on the fact that I'm unable to generate a new table after resetting the previous table.
What I would like to do is to let a user reset the table using the button and then generate another one if needed, and not needing him to reload the page. However, I am unsure why my codes only allow me to reset the table but am unable to generate another table.
Any help on this would be greatly appreciated.
function generate() {
var myTable = document.getElementById("generatedTable");
var table = document.createElement('TABLE');
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var rows = document.getElementById("rows").value;
var cols = document.getElementById("cols").value;
for (var y = 0; y < rows; y++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var x = 0; x < cols; x++) {
var td = document.createElement('TD');
td.width = 10;
td.height = 10;
var cellID = "cell [" + x + ", " + y + "]";
td.setAttribute("id", cellID.toString());
td.addEventListener("click", function() {
cellClicked(this);
});
td.appendChild(document.createTextNode("Cell " + x + "," + y));
tr.appendChild(td);
}
myTable.appendChild(table);
}
//document.getElementById("button").disabled = true;
}
function cellClicked(cell) {
//var cell = document.getElementById("this");
cell.style.backgroundColor = "yellow";
}
function mouseOver(cell) {
var cell = document.getElementById("td");
cell.style.backgroundColor = "red";
}
function mouseOut(cell) {
var cell = document.getElementById("generatedTable");
cell.style.backgroundColor = "";
}
function removeTable() {
var removeTab = document.getElementById('generatedTable');
var parentElement = removeTab.parentElement;
parentElement.removeChild(removeTab);
}
No. of Rows <input type="text" name="rows" id="rows">
<br>
<br> No. of Cols <input type="text" name="cols" id="cols">
<br>
<button onclick="generate()" type="button" id="button">Generate</button>
<button onclick="removeTable()" type="reset" value="reset">RESET TABLE</button>
<table id="generatedTable" onmouseover="mouseOver()" onmouseout="mouseOut()"></table>
You were using the id "generatedTable" in a confusing way, at the same time for the newly generated table and for the table you already had in your html file. And at the end you were removing the wrapper table instead of the newly generated one.
It is maybe easier to understand if you use a target element and add the table in it:
const wrapper = document.getElementById('table-wrapper');
function generate() {
var table = document.createElement('TABLE');
table.id = 'generatedTable';
table.border = '1';
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
var rows = document.getElementById("rows").value;
var cols = document.getElementById("cols").value;
for (var y = 0; y < rows; y++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var x = 0; x < cols; x++) {
var td = document.createElement('TD');
td.width = 10;
td.height = 10;
var cellID = "cell [" + x + ", " + y + "]";
td.setAttribute("id", cellID.toString());
td.addEventListener("click", function() {
cellClicked(this);
});
td.appendChild(document.createTextNode("Cell " + x + "," + y));
tr.appendChild(td);
}
wrapper.appendChild(table);
}
//document.getElementById("button").disabled = true;
}
function cellClicked(cell) {
//var cell = document.getElementById("this");
cell.style.backgroundColor = "yellow";
}
function mouseOver(cell) {
var cell = document.getElementById("td");
cell.style.backgroundColor = "red";
}
function mouseOut(cell) {
var cell = document.getElementById("generatedTable");
cell.style.backgroundColor = "";
}
function removeTable() {
var removeTab = document.getElementById('generatedTable');
wrapper.removeChild(removeTab);
}
No. of Rows <input type="text" name="rows" id="rows">
<br>
<br> No. of Cols <input type="text" name="cols" id="cols">
<br>
<button onclick="generate()" type="button" id="button">Generate</button>
<button onclick="removeTable()" type="reset" value="reset">RESET TABLE</button>
<div id="table-wrapper"></div>

Creating a JS function that colors a specific cell

I am trying to create a separate function that once a table has been generated, a value x and y can be placed within the input and it will highlight the desired cell a certain colour.
My issue arises when I try to select the cell specifically, my code breaks down at
var change = document.getElementById("table").tr[rowIndex].td[cellIndex];
// functions to create values of r and c
function GenerateTable() {
var tblBody = document.createElement("tbody");
for (var i = 0; i < irow.value; i++) {
var row = document.createElement("tr");
for (var j = 0; j < icol.value; j++) {
var cell = document.createElement("td");
row.appendChild(cell)
}
tblBody.appendChild(row);
}
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
//selector function
function SelectCell() {
//grab value from the input x and y
var tr = document.getElementsByTagName("tr");
var td = document.getElementsByTagName("td");
//insert the value of x and y into an array retriever
var rowIndex = document.getElementById("valy").value;
var cellIndex = document.getElementById("valx").value;
//*********BREAKS DOWN HERE*******
var change = document.getElementById("table").tr[rowIndex].td[cellIndex];
change.style.backgroundColor = "red";
//change color of specific coord
}
<label>Rows</label>
<input type="number" id="irow">
<label>Cols</label>
<input type="number" id="icol">
<input type="submit" id="smit1">
<input type="number" id="valx" placeholder="x">
<input type="number" id="valy" placeholder="y">
<input type="submit" id="smit2">
<table id="table">
</table>
I'm not sure you can chain it like this:
var change = document.getElementById("table").tr[rowIndex].td[cellIndex];
I think what you want is:
//grab value from the input x and y
var rowIndex = +document.getElementById('valy').value;
var cellIndex = +document.getElementById('valx').value;
// Get reference to the table
var table = document.getElementById('table');
// Get the tr of the table with the index rowIndex
var tr = table.querySelectorAll('tr')[rowIndex];
// Query the selected row for all column elements and select the one at the needed index
var change = tr.querySelectorAll('td')[cellIndex];
NOTE: It's probably best to validate the values in the input before trying to retrieve the DOM element to ensure the code does not break if the user enters a non integer value or a value which is out of bounds
Since I finished it anyway:
Here is a working example
var irow = document.querySelector('#irow');
var icol = document.querySelector('#icol');
var smit1 = document.querySelector('#smit1');
var valx = document.querySelector('#valx');
var valy = document.querySelector('#valy');
var smit2 = document.querySelector('#smit2');
function GenerateTable() {
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
for (var i = 0; i < irow.value; i++) {
var row = document.createElement("tr");
for (var j = 0; j < icol.value; j++) {
var cell = document.createElement("td");
row.appendChild(cell)
}
tblBody.appendChild(row);
}
tbl.setAttribute('class', 'generated');
tbl.appendChild(tblBody);
body.appendChild(tbl);
smit1.disabled = true;
irow.disabled = true;
icol.disabled = true;
smit2.disabled = false;
valx.disabled = false;
valy.disabled = false;
}
function SelectCell() {
var tr = document.getElementsByTagName("tr");
var td = document.getElementsByTagName("td");
var rowIndex = valy.value;
var cellIndex = valx.value;
var change = document.querySelector('table.generated tbody').children[rowIndex].children[cellIndex];
change.style.backgroundColor = "red";
}
smit1.addEventListener('click', GenerateTable);
smit2.addEventListener('click', SelectCell);
table.generated td {
width: 10px;
height: 10px;
border: 1px solid #000000;
}
.width100 {
width: 100%;
}
<body>
<div class="width100">
<input type="number" id="irow" placeholder="rows">
<input type="number" id="icol" placeholder="cols">
<input type="submit" id="smit1">
</div>
<div class="width100">
<input type="number" id="valx" disabled="true" placeholder="x">
<input type="number" id="valy" disabled="true" placeholder="y">
<input type="submit" id="smit2" disabled="true">
</div>
</body>

javascript dyanmic table add / delete row

I am trying to build a form for creating a list for image deployment.
I am able to create a dynamic table on form load and also collect the data for each value, but can seem to get the Add and Delete working.
My Question:
What must I do(or change) in my code to get the ADD and Delete options working and to export the table data in CSV format.
Please could someone help and/or guide me as I am getting so lost and really would like a working example .. there is so much on the net it's over-whelming
Newest place I visited is Mozilla DOM help pages what's confusing is how to load your own variables into the table
For reference I used stackoverflow and plenty google and finally this site
Here is my code:
<div id="metric_results">
Enter Target Name:
<input type="text" name="textbox1" id="textbox1" VALUE="win2k8"/>
<br>
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
<input type="button" id="create" value="Add Row" onclick="Javascript:addRow()">
<input type="button" id="create" value="Delete Row" onclick="Javascript:deleteRow()">
</div>
<SCRIPT LANGUAGE="JavaScript">
window.onload =addTable;//loads table on window loading
function addTable() {
var myTableDiv = document.getElementById("metric_results")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
var imageName = textbox1.value
table.border = '1'
table.appendChild(tableBody);
var heading = new Array();
heading[0] = "imageName"
heading[1] = "acceptAllEula"
heading[2] = "noSSLverify"
heading[3] = "noVerification"
heading[4] = "TargetImagelocation"
heading[5] = "Username"
heading[6] = "Password"
heading[7] = "Target IP"
var imageInfo = new Array()
imageInfo[0] = new Array(imageName, "acceptAllEula", "noSSLverify", "noVerification", "testLocation", "user", "pass", "192.168.1.151")
imageInfo[1] = new Array("win2008", "acceptAllEula", "noSSLverify", "noVerification", "testLocation", "user", "pass", "192.168.1.151")
//TABLE COLUMNS
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (i = 0; i < heading.length; i++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[i]));
tr.appendChild(th);
}
//TABLE ROWS
for (i = 0; i < imageInfo.length; i++) {
var tr = document.createElement('TR');
for (j = 0; j < imageInfo[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(imageInfo[i][j]));
tr.appendChild(td)
}
tableBody.appendChild(tr);
}
myTableDiv.appendChild(table)
}
function addRow() {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell3.appendChild(element2);
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
</SCRIPT>
You're not setting any id to the table you're creating onload - so when you later come to call getElementById() inside addRow it cannot be found (and you're using a variable which does not exist - tableID!)
My suggestion is to take an id as a parameter to addTable, and set that as the id of the dynamically generated table:
function addTable(id) {
var myTableDiv = document.getElementById("metric_results")
var table = document.createElement('TABLE')
table.id = id;
....
onload, pass somethig sensible - default perhaps:
window.onload = function(){
addTable("default");
}
And either pass this in when adding a row, or use the default provided above:
function addRow() {
var table = document.getElementById("default");
....
or
function addRow(id) {
var table = document.getElementById(id);
Updated fiddle: https://jsfiddle.net/egtu5kay/5/
Left as an exercise for you: Correctly formatting the new row as you wish.

get All the text fields data from the html table

Get All the data values from the auto generated table and show these values through loop to user by JavaScript alert.I have implemented but it is not showing anything in alert.how i can take the values from these autogenrated text fields.
function myFunction() {
var table = document.getElementById("myTable");
var table1 = document.getElementById("myTable").length;
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var textf1 = '<div>FirstName:<input type="text" value="Enter Your Name" id="text1" /></div>';
var textf2 = '<div>LastName:<input type="text" value="Enter Your Surname" id="text2" /></div>';
cell1.innerHTML = textf1;
cell2.innerHTML = textf2;
}
function first(){
var x = document.getElementById("myTable");
var textn = "";
var texts= "";
var i;
var a;
for (i = 0; i < x.length ;i++) {
textn += text1[i].value + "<br>";
}
for (a = 0; i < x.length ;i++) {
texts += text2[i].value + "<br>";
}
alert("First Name:"+textn"Second Name:"+texts);
/*var table1 = document.getElementById("myTable").length;
for(var row = 0; row <= table1;row++ ) {
alert("Hello" + text1.value(i) + "Your Surname Is " + text2.value(i) + " You Have Chosen");
}
/*return myFunction()*/
}
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/myweb.js">
</script>
</head>
<body>
<p>Click the button to add a new row at the first position of the table and then add cells and content.</p>
<table id="myTable"></table>
<table id="myTable1"></table>
<br>
<div id="first"></div>
<button onclick="myFunction()">Add Your First row</button>
<button onclick="first()">Submit</button>
</body>
</html>
function first(){
var x = document.getElementById("myTable");
var inputElements = x.querySelectorAll('input, select, textarea');
for(var i = 0; i < inputElements.length; i++){
alert(inputElements[i].value);
}
}
alert("First Name:"+textn"Second Name:"+texts);
Missing +
alert("First Name:"+textn+"Second Name:"+texts);

How can I use for loop to newline the table and clear the data?

I want to use forloop to new line the data (not in a row) and when I click the button, clear the last data (but remain the original title--id.lat.lng.speed.rpm.angle.state.time).
Extra, I found at the row back 2 fields aren't have any data. (WHY? Can I remove it?)
<!DOCTYPE html>
<%# page language="java" contentType="text/html;charset=utf-8" import="java.io.*" import="java.util.*" import="java.sql.*"%>
<html>
<head>
<script>
function click_x(clicked_id){
var xxx=[];
xxx[0] = [0,1,2,3,4,5,6,7];
xxx[1] = [8,9,10,11,12,13,14,15];
xxx[2] = [16,17,18,19,20,21,22,23];
xxx[3] = [24,25,26,27,28,29,30,31];
xxx[4] = [32,33,34,35,36,37,38,39];
xxx[5] = [40,41,42,43,44,45,46,47];
var table = document.getElementById("myTable");
var row1 = table.insertRow(1);
var cell1 = row1.insertCell(0);
var markersControlArray = [true,true,true,false,false];
for(var k = 0 ; k < markersControlArray.length ; k++){
if(markersControlArray[k] == true){
for(var i = 0; i < 8 ; i++){
cell1 = row1.insertCell(i);
cell1.innerHTML = xxx[k][i];
}
}
}
}
</script>
</head>
<body>
<table id="myTable" border="3">
<tr>
<th>Id</th>
<th>Lat</th>
<th>Lng</th>
<th>Speed</th>
<th>Rpm</th>
<th>Angle</th>
<th>State</th>
<th>Time</th>
</tr>
</table><br>
<button id="1" onClick="click_x(this.id)">Submit</button>
</body>
</html>
What you need is to insert new row in a table for each xxx[k] with insertRow method. You should do it at the beginning of the outer for loop. So the loops should look something like that:
for(var k = 0 ; k < markersControlArray.length ; k++){
if(markersControlArray[k] == true){
var row1 = table.insertRow(-1);
for(var i = 0; i < 8 ; i++){
var cell1 = row1.insertCell(i);
cell1.innerHTML = xxx[k][i];
}
}
}
Those empty cells are there because you create them before the loops, with this code:
var cell1 = row1.insertCell(0);
var cell2 = row1.insertCell(1);
Whole JavaScript code:
function click_x(clicked_id){
var xxx=[];
xxx[0] = [0,1,2,3,4,5,6,7];
xxx[1] = [8,9,10,11,12,13,14,15];
xxx[2] = [16,17,18,19,20,21,22,23];
xxx[3] = [24,25,26,27,28,29,30,31];
xxx[4] = [32,33,34,35,36,37,38,39];
xxx[5] = [40,41,42,43,44,45,46,47];
var table = document.getElementById("myTable");
var markersControlArray = [true,true,true,false,false,true]; // you have missed value for xxx[5] - I added it
for(var k = 0 ; k < markersControlArray.length ; k++){
if(markersControlArray[k] == true){
var row1 = table.insertRow(-1);
for(var i = 0; i < 8 ; i++){
var cell1 = row1.insertCell(i);
cell1.innerHTML = xxx[k][i];
}
}
}
}
Check working fiddle.
In general I see that you have used code from some tutorial and didn't analyze it well enough and didn't remove unneeded code.
<!DOCTYPE html>
<html>
<head>
<script>
function arrRow(tableId){
var table = document.getElementById(tableId);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
return row;
}
function click_x(clicked_id){
var xxx=[];
xxx[0] = [0,1,2,3,4,5,6,7];
xxx[1] = [8,9,10,11,12,13,14,15];
xxx[2] = [16,17,18,19,20,21,22,23];
xxx[3] = [24,25,26,27,28,29,30,31];
xxx[4] = [32,33,34,35,36,37,38,39];
xxx[5] = [40,41,42,43,44,45,46,47];
var table = document.getElementById("myTable");
var markersControlArray = [true,true,true,false,false];
for(var k = 0 ; k < markersControlArray.length ; k++){
if(markersControlArray[k] == true){
var RowVar = arrRow("myTable");
for(var i = 0; i < 8 ; i++){
cell1 = RowVar.insertCell(i);
cell1.innerHTML = xxx[k][i];
}
}
}
}
</script>
</head>
<body>
<table id="myTable" border="3">
<tr>
<th>Id</th>
<th>Lat</th>
<th>Lng</th>
<th>Speed</th>
<th>Rpm</th>
<th>Angle</th>
<th>State</th>
<th>Time</th>
</tr>
</table><br>
<button id="1" onClick="click_x(this.id)">Submit</button>
</body>
</html>

Categories

Resources