Set 3 values in an array - dynamic table row javascrip - javascript

I have a dynamic table and when i add a row i want to save the data from input.
I can save the data but all inside one array,i want to set just 3 values each sub array.
Because one row have 3 inputs.
But i´m having some difficulties.
I'm new to javascript and here at stack overflow
Can you help me please?
function arraySaveData() {
var data = [];
for (var index = 0; index < 1; index++) {
$('#mytableform1').each(function (_, element) {
var element = document.getElementsByName("namesavedata[]");
for (var i = 0; i < element.length; i++) {
data.push(element[i].value);
}
});
var result = [];
for(var i = 0; i < data.length; i++) {
var obj = {}
obj= data[i];
result.push(obj)
}
console.log(result)
}
}
//Button add table row
function addRow() {
var table = document.getElementById("mytableform1");
var rowCount = table.rows.length;
x = document.getElementById("mytableform1").rows.length;
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
//numeração crescente
for (var i = 0; i < x; i++) {
cell1.innerHTML = '<input type="text" class="form-control" name="namesavedata[]" align="center" placeholder="' +
(cell1.innerHTML = i + 0) +
'">';
cell2.innerHTML = '<input type="text" class="form-control" name="namesavedata[]" align="center" placeholder="00000,000">';
cell3.innerHTML = '<input type="text" class="form-control" name="namesavedata[]" align="center" placeholder="00000,000">';
}
}
//Button delete table row
function deleteRow() {
var table = document.getElementById("mytableform1");
var rowCount = table.rows.length;
if (rowCount >= 4) {
table.deleteRow(rowCount - 1);
} else {
Swal.fire({
title: 'Erro!',
text: "Não pode apagar este campo",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#e55353',
cancelButtonColor: '#636f83',
confirmButtonText: 'ok'
})
}
}
<table id="mytableform1" width="100%" border="1" cellspacing="0" cellpadding="0" style="border: 1px solid;color: #5c6873;background-color: #fff;border-color: #e4e7ea;">
<tr>
<td rowspan="2" align="center" valign="top">Vértices da poligonal</td>
<td colspan="3" align="center" valign="top">Coordenadas no sistema PT - TM06/ETRS89</td>
</tr>
<tr>
<td align="center" valign="top">M(m)</td>
<td align="center" valign="top">P(m)</td>
</tr>
<tr name="allDataRow">
<td align="center" valign="top">
<input style="width: 100%;" class="form-control" type="number" name="namesavedata[]" id="val_1" placeholder="1">
</td>
<td align="center" valign="top">
<input style="width: 100%;" class="form-control" type="number" name="namesavedata[]" id="val_2" placeholder="00000,000">
</td>
<td align="center" valign="top">
<input style="width: 100%;" class="form-control" type="number" name="namesavedata[]" id="val_3" placeholder="00000,000">
</td>
</tr>
</table>
<div style="display:flex;justify-content: space-between;">
<div style="display:flex;">
<button onclick="addRow()" style="background-color: #673ab7c7;color: white;" class="btn" type="button">
<span class="bi bi-plus-square-dotted"></span>+
</button>
<button onclick="deleteRow()" style="background-color: #673ab7c7;color: white;" class="btn" type="button">
<span class="bi bi-plus-square-dotted"></span>-
</button>
</div>
<div style="display:flex;">
<button type="button" name="button" onclick="arraySaveData()" class="btn" style="background-color: #673ab7c7;color: white;">
Validar dados da tabela
</button>
</div>
</div>

Your issue is that you are creating an object and then reassigning it to the value of data[i]. This is then being pushed to your array, rather than an object, so you are getting an array of values rather than an array of objects.
Change this line of code:
var obj = {};
obj = data[i];
result.push(obj); // Add data[i] to the results array.
To this:
var obj = {data[i]};
result.push(obj); // Add an object containing data[i] to the results array
Now, you are pushing the object with the value of data[i] inside.
Or if you want to have three sub-arrays as in your question:
var tableCell = [data[i]];
result.push(tableCell);
If you run this code snippet, you can see what's happening when you reassign obj to data[i]:
const data = ["foo","bar"];
var obj = {};
console.log(obj);
// output: {}
obj = data[0];
console.log(obj);
// output: "foo"

Related

How to read data into an array from a dynamic table AND validate data when added more rows

I am just starting to program with javascript and I ran into this difficulty:
I created a dynamic table in html and javascript. I have already created the function to add rows and delete.
But I am having some difficulty in saving the received data into the array. It only saves the first row into the array. I want it to loop and save all the respective data in the array.
type here
My html code:
<table id="mytableform1" width="100%" border="1" cellspacing="0" cellpadding="0" style="border: 1px solid;color: #5c6873;background-color: #fff;border-color: #e4e7ea;">
<tr>
<td rowspan="2" align="center" valign="top">Vértices da poligonal</td>
<td colspan="3" align="center" valign="top">Coordenadas no sistema PT - TM06/ETRS89</td>
</tr>
<tr>
<td align="center" valign="top">M(m)</td>
<td align="center" valign="top">P(m)</td>
</tr>
<tr id="allDataRow">
<td align="center" valign="top">
<input style="width: 100%;" class="form-control" type="number" name="namesavedata1[]" id="val_1" placeholder="1">
</td>
<td align="center" valign="top">
<input style="width: 100%;" class="form-control" type="number" name="namesavedata2[]" id="val_2"placeholder="00000,000">
</td>
<td align="center" valign="top">
<input style="width: 100%;" class="form-control" type="number" name="namesavedata3[]" id="val_3" placeholder="00000,000">
</td>
</tr>
</table>
<div style="display:flex;justify-content: space-between;">
<div style="display:flex;">
<button onclick="addRow()" style="background-color: #673ab7c7;color: white;" class="btn" type="button">
<span class="bi bi-plus-square-dotted"></span>+
</button>
<button onclick="deleteRow()" style="background-color: #673ab7c7;color: white;" class="btn" type="button">
<span class="bi bi-plus-square-dotted"></span>-
</button>
</div>
<div style="display:flex;">
<button type="button" name="button" onclick="arraySaveData()" class="btn" style="background-color: #673ab7c7;color: white;">
Validar
</button>
</div>
</div>
My Javascript code:
function arraySaveData() {
var data = [];
//var dataMain = [];
//for (var index = 0; index < 1; index++) {
$('#mytableform1').each(function () {
data.push({
verticePolig: $('input[name="namesavedata1[]"]').val(),
});
data.push({
coordM: $('input[name="namesavedata2[]"]').val(),
});
data.push({
coordP: $('input[name="namesavedata3[]"]').val(),
});
});
console.log(data);
//dataMain.push(data);
//}
//console.log(dataMain);
}
//Button add table row
function addRow() {
var table = document.getElementById("mytableform1");
var rowCount = table.rows.length;
x = document.getElementById("mytableform1").rows.length;
var row = table.insertRow();
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
//numeração crescente
for (var i = 0; i < x; i++) {
cell1.innerHTML = '<input type="text" class="form-control" name="namesavedata1[]" align="center" placeholder="' +
(cell1.innerHTML = i + 0) +
'">';
cell2.innerHTML = '<input type="text" class="form-control" name="namesavedata2[]" align="center" placeholder="00000,000">';
cell3.innerHTML = '<input type="text" class="form-control" name="namesavedata3[]" align="center" placeholder="00000,000">';
}
}
//Button delete table row
function deleteRow() {
var table = document.getElementById("mytableform1");
var rowCount = table.rows.length;
if (rowCount >= 4) {
table.deleteRow(rowCount - 1);
} else {
Swal.fire({
title: 'Erro!',
text: "Não pode apagar este campo",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#e55353',
cancelButtonColor: '#636f83',
confirmButtonText: 'ok'
})
}
}
The problem is in the loop you have to add the data. You always take the same 3 inputs in each loop.
You should receive the current element in the callback function for each loop it makes, something like the example below:
$('#mytableform1').each(function (_, element) {
// element is the current row <tr id="allDataRow">
// now you find children element value
const verticePolig = $(element).find('namesavedata1[]').val()
const coordM = $(element).find('namesavedata2[]').val()
const coordP = $(element).find('namesavedata3[]').val()
data.push({
verticePolig,
coordM,
coordP
})
});

HTML/JS output table not showing horizontal borders

I can't figure out why my horizontal borders are not showing up with my output section. See code and screenshot below:
I would like to have horizontal borders and if possible keep the date fields from
wrapping into the next row below itself.
I would like to have horizontal borders and if possible keep the date fields from wrapping into the next row below itself.
<td align="center"><input type="button" value="Submit" name="submit" id="submit" onClick="display()" /></button></td>
</tr>
</table>
<table width="400px" align="center" colspan="40" table border="5">
<tr style="background-color:#8FBC8F;">
<td align="center"><b>Name</b></td>
<td align="center"><b>Company</b></td>
<td align="center"><b>Time In</b></td>
<td align="center"><b>Time Out</b></td>
<td align="center"><b>Description of Work</b></td>
</tr>
<tr>
<td align="center"><div id="displayarea"></div></td>
<td align="center"><div id="displayarea1"></div></td>
<td align="center"><div id="displayarea2"></div></td>
<td align="center"><div id="displayarea3"></div></td>
<td align="center"><div id="displayarea4"></div></td>
</tr>
I would like to have horizontal borders and if possible keep the date fields from wrapping into the next row below itself.
function getValue() {
var Items = "";
var td1 = document.getElementById("displayarea").innerHTML.split("<br>");
var td2 = document.getElementById("displayarea1").innerHTML.split("<br>");
var td3 = document.getElementById("displayarea2").innerHTML.split("<br>");
var td4 = document.getElementById("displayarea3").innerHTML.split("<br>");
var td5 = document.getElementById("displayarea4").innerHTML.split("<br>");
for (var i = 0; i < td1.length; i++) {
if (td1[i])
Items += td1[i] + " ,";
if (td2[i])
Items += td2[i] + " ,";
if (td2[i])
Items += td2[i] + " ,";
if (td3[i])
Items += td3[i] + " ,";
if (td4[i])
Items += td4[i] + " ";
Items += "\n";
}
console.log(Items);
return Items;
}
function display() {
document.getElementById("displayarea").innerHTML += document.getElementById("fname").value + "<br />";
document.getElementById("fname").value = "";
document.getElementById("displayarea1").innerHTML += document.getElementById("lname").value + "<br />";
document.getElementById("lname").value = "";
document.getElementById("displayarea2").innerHTML += document.getElementById("sname").value + "<br />";
document.getElementById("sname").value = "";
document.getElementById("displayarea3").innerHTML += document.getElementById("pname").value + "<br />";
document.getElementById("pname").value = "";
document.getElementById("displayarea4").innerHTML += document.getElementById("jname").value + "<br />";
document.getElementById("jname").value = "";
}
I highly suggest you start separating your data from your presentation of that data.
So, split your display function into two: createRow and renderRows. Likewise, getValues can just be getRows.
Note that this required a different way of doing things in your code, so I also refactored your HTML and CSS to bring it more in line with modern methods.
function getRows(data) {
return data.map(datum => Object.values(datum).join(',')).join('\n');
}
function createRow(data) {
const datum = {
fname: document.getElementById("fname").value,
lname: document.getElementById("lname").value,
sname: new Date(document.getElementById("sname").valueAsNumber).toLocaleString(),
pname: new Date(document.getElementById("pname").valueAsNumber).toLocaleString(),
jname: document.getElementById("jname").value
};
data.push(datum);
document.getElementById("dataForm").reset();
renderRows(data);
}
function renderRows(data) {
const body = document.getElementById("renderedData");
body.innerHTML = "";
for (let datum of data) {
let tr = document.createElement('tr');
let tdFName = document.createElement('td');
tdFName.appendChild(document.createTextNode(datum.fname));
tr.appendChild(tdFName);
let tdLName = document.createElement('td');
tdLName.appendChild(document.createTextNode(datum.lname));
tr.appendChild(tdLName);
let tdSName = document.createElement('td');
tdSName.appendChild(document.createTextNode(datum.sname));
tr.appendChild(tdSName);
let tdPName = document.createElement('td');
tdPName.appendChild(document.createTextNode(datum.pname));
tr.appendChild(tdPName);
let tdJName = document.createElement('td');
tdJName.appendChild(document.createTextNode(datum.jname));
tr.appendChild(tdJName);
body.appendChild(tr);
}
}
window.addEventListener('load', () => {
const data = [];
document.getElementById('add').addEventListener('click', function(e) {
createRow(data);
});
document.getElementById('getData').addEventListener('click', function(e) {
console.log(getRows(data));
});
});
form {
width: max-content;
margin: 0 auto 1rem;
}
.control-group {
display: flex;
justify-content: space-between;
}
fieldset {
display: flex;
flex-flow: column nowrap;
}
fieldset button {
align-self: flex-end;
}
<form id="dataForm">
<fieldset>
<legend>Enter Data</legend>
<div class="control-group">
<label for="fname">Name:</label>
<input id="fname" type="text">
</div>
<div class="control-group">
<label for="lname">Company:</label>
<input id="lname" type="text">
</div>
<div class="control-group">
<label for="sname">Time In:</label>
<input id="sname" type="datetime-local">
</div>
<div class="control-group">
<label for="pname">Time Out:</label>
<input id="pname" type="datetime-local">
</div>
<div class="control-group">
<label for="jname">Description of Work:</label>
<textarea id="jname"></textarea>
</div>
<button type="button" id="add">Add</button>
</fieldset>
</form>
<table width="400px" align="center" colspan="40" table border="5">
<thead>
<tr style="background-color:#8FBC8F;" id='header'>
<td align="center"><b>Name</b></td>
<td align="center"><b>Company</b></td>
<td align="center"><b>Time In</b></td>
<td align="center"><b>Time Out</b></td>
<td align="center"><b>Description of Work</b></td>
</tr>
</thead>
<tbody id="renderedData">
</tbody>
</table>
<button type="button" id="getData">Get Data</button>
To get borders for all cells, add this at the top of your html code (inside the head):
<style>
table {
border-collapse: collapse;
}
td {
border: 1px solid #555;
}
</style>
Adjust the border thickness, style and color as you like (in the border setting of td)
Here's an easy way to add a row with each addition using the element - available in all good browsers (not so fast Internet Explorer, I wasn't talking to you)
I've also changed how to read the values
note, using class instead of id in the cells in the rows - to make it easy to get them all with minimal change to your code
Although, personally I'd get the row data data differently (shown in alternativeGetValues)
function getValue() {
var Items = "";
var td1 = [...document.querySelectorAll(".displayarea")].map(e => e.innerHTML);
var td2 = [...document.querySelectorAll(".displayarea1")].map(e => e.innerHTML);
var td3 = [...document.querySelectorAll(".displayarea2")].map(e => e.innerHTML);
var td4 = [...document.querySelectorAll(".displayarea3")].map(e => e.innerHTML);
var td5 = [...document.querySelectorAll(".displayarea4")].map(e => e.innerHTML);
for (var i = 0; i < td1.length; i++) {
if (td1[i])
Items += td1[i] + " ,";
if (td2[i])
Items += td2[i] + " ,";
if (td3[i])
Items += td3[i] + " ,";
if (td4[i])
Items += td4[i] + " ,";
if (td5[i])
Items += td5[i] + " ";
Items += "\n";
}
console.log(Items);
return Items;
}
function display() {
const template = document.getElementById("row");
const clone = template.content.cloneNode(true);
const additem = (dest, src) => {
const s = document.querySelector(src);
clone.querySelector(dest).innerHTML = s.value;
s.value = "";
};
additem(".displayarea", "#fname");
additem(".displayarea1", "#lname");
additem(".displayarea2", "#sname");
additem(".displayarea3", "#pname");
additem(".displayarea4", "#jname");
template.insertAdjacentElement('beforebegin', clone.firstElementChild);
}
// IMHO this is better
function alternateGetValue() {
const Items = [...document.querySelectorAll('.data')]
.map(row => [...row.querySelectorAll('td>div')]
.map(d => d.textContent).join(',')
).join('\n');
console.log(Items);
return Items;
}
.wide {
min-width:12em;
}
F: <input id="fname"> <br>
L: <input id="lname"> <br>
S: <input id="sname"> <br>
P: <input id="pname"> <br>
J: <input id="jname"> <br>
<input type="button" value="add" onclick="display()"/>
<input type="button" value="show" onclick="getValue()"/>
<input type="button" value="Better" onclick="alternateGetValue()"/>
<table width="400px" align="center" colspan="40" table border="5">
<thead>
<tr style="background-color:#8FBC8F;" id='header'>
<td align="center"><b>Name</b></td>
<td align="center"><b>Company</b></td>
<td align="center" class="wide"><b>Time In</b></td>
<td align="center" class="wide"><b>Time Out</b></td>
<td align="center"><b>Description of Work</b></td>
</tr>
</thead>
<tbody>
<template id="row">
<tr style="background-color:#8F8FBC;" class="data">
<td align="center"><div class="displayarea"></div></td>
<td align="center"><div class="displayarea1"></div></td>
<td align="center"><div class="displayarea2"></div></td>
<td align="center"><div class="displayarea3"></div></td>
<td align="center"><div class="displayarea4"></div></td>
</tr>
</template>
</tbody>
</table>

Show calculated arithmetic mean in <td> when the button is clicked

please help me finish this, I'm getting nowhere.
what needs to be done
final results
I've explained in the pictures whats the finish goal.
This is a grade calculator.
There are 3 types of grades.. it should calculate the arithmetic mean for every category and arithmetic mean for all grades no matter which category they are.
Calculated values should be shown on the appropriate block, as shown in the picture.
input[type="number"]{
color : transparent;
text-shadow : 0 0 0 #000;
}
input[type="number"]:focus{
outline : none;
}
</style>
<body>
<div id="stranica" style="display: inline-block; position: left;">
<button type="button" onclick="javascript:dodajocenu();"> Add grade</button>
</div>
<div id="desna" style="display: inline-block; position: absolute; text-align: center;">
<button type="button" onclick=""> Calculate </button>
<br><br>
<table border="1">
<tbody>
<tr>
<td style="width:70px; text-align: center;">Written test</td>
<td style="width:70px; text-align: center;">Essay</td>
<td style="width:70px; text-align: center;">Class Activity</td>
</tr>
<tr>
<td style="text-align: center;"> </td> <!-- insert arithmetic mean of all Writtentest, inside td-->
<td style="text-align: center;"></td> <!-- insert arithmetic mean of all Essay, inside td-->
<td style="text-align: center;"></td> <!-- insert arithmetic mean of all ClassActivity, inside td-->
</tr>
</tbody>
</table>
<br>
<table border="1">
<tbody>
<tr>
<td style="width:140px; text-align: center;">Arithmetic mean of all grades</td>
</tr>
<tr>
<td style="text-align: center;"> </td> <!-- insert arithmetic mean of all numbers-->
</tr>
</tbody>
</table>
</div>
</body>
<script>
var ocena = 0;
var stranica = document.querySelector("#stranica")
function removeElement(obrisi) {
var dugme = obrisi.target;
stranica.removeChild(dugme.parentElement)
}
function dodajocenu() {
ocena++;
//create textbox
var input = document.createElement('input');
input.type = "number";
input.setAttribute("max",5);
input.setAttribute("min",1);
var myParent = document.body;
//Create array of options to be added
var array = ["Written test","Essay","Class Activity"];
//Create and append select list
var selectList = document.createElement('select');
selectList.id = "mySelect";
myParent.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement('option');
option.value = array[i];
option.text = array[i];
selectList.appendChild(option);
}
//create remove button
var remove = document.createElement('button');
remove.onclick = function(obrisiocenu) {
removeElement(obrisiocenu);
}
remove.setAttribute("type", "dugme");
remove.innerHTML = "-"; //delete
var item = document.createElement('div')
item.classList.add("item")
item.appendChild(input);
item.appendChild(selectList);
item.appendChild(remove);
stranica.appendChild(item)
}
</script>```
var ocena = 0;
function removeElement(obrisi) {
var dugme = obrisi.target;
document.getElementById("stranica").removeChild(dugme.parentElement)
}
function dodajocenu() {
ocena++;
//create textbox
var input = document.createElement('input');
input.type = "number";
input.setAttribute("max", 5);
input.setAttribute("min", 1);
var myParent = document.body;
//Create array of options to be added
var array = ["Kontrolni", "Vezbe", "Aktivnost"];
//Create and append select list
var selectList = document.createElement('select');
selectList.id = "mySelect";
myParent.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement('option');
option.value = array[i];
option.text = array[i];
selectList.appendChild(option);
}
//create remove button
var remove = document.createElement('button');
remove.onclick = function(obrisiocenu) {
removeElement(obrisiocenu);
}
remove.setAttribute("type", "dugme");
remove.innerHTML = "-"; //delete
var item = document.createElement('div')
item.classList.add("item")
item.appendChild(input);
item.appendChild(selectList);
item.appendChild(remove);
document.getElementById("stranica").appendChild(item)
}
function calcMean() {
var nameList=document.querySelectorAll('#stranica .item #mySelect');
var inputList=document.querySelectorAll('#stranica .item input');
var kontrolniList = [];
var vezbeList = [];
var aktivnostList = [];
var ocenaList = [];
for(var i=0; i< nameList.length; i++){
ocenaList.push(parseInt(inputList[i].value));
if(nameList[i].value=='Kontrolni') {
kontrolniList.push(parseInt(inputList[i].value));
}
else if(nameList[i].value=='Vezbe') {
vezbeList.push(parseInt(inputList[i].value));
}
else if(nameList[i].value=='Aktivnost') {
aktivnostList.push(parseInt(inputList[i].value));
}
}
document.getElementById("kontrolni").innerHTML=avg(kontrolniList);
document.getElementById("vezbe").innerHTML=avg(vezbeList);
document.getElementById("aktivnost").innerHTML=avg(aktivnostList);
document.getElementById("ocena").innerHTML=avg(ocenaList);
}
function avg( arr ) {
var total = 0, i;
for (i = 0; i < arr.length; i += 1) {
total += arr[i];
}
return total / arr.length;
}
<div id="stranica" style="display: inline-block; position: left;">
<button type="button" onclick="javascript:dodajocenu();"> Dodaj ocenu</button>
</div>
<div id="desna" style="display: inline-block; position: absolute; text-align: center;">
<button type="button" onclick="javascript:calcMean();"> Izracunaj prosek</button>
<br><br>
<table border="1">
<tbody>
<tr>
<td style="width:70px; text-align: center;">Kontrolni</td>
<td style="width:70px; text-align: center;">Vezbe</td>
<td style="width:70px; text-align: center;">Aktivnost</td>
</tr>
<tr>
<td id="kontrolni" style="text-align: center;"> </td>
<td id="vezbe" style="text-align: center;"></td>
<td id="aktivnost" style="text-align: center;"></td>
</tr>
</tbody>
</table>
<br>
<table border="1">
<tbody>
<tr>
<td style="width:140px; text-align: center;">Zakljucna ocena</td>
</tr>
<tr>
<td id="ocena" style="text-align: center;"> </td>
</tr>
</tbody>
</table>
</div>
Hope this will work.

oninput event in html works fine till <form></form> is added?

I am adding rows in table and deleting, this works fine. using oninput="" event i am also able to calculate the total cost by calling javascript function.
Now, the moment i add <form></form>, neither am able to add rows nor moving any forward. I am new to javascript, and have no clue what is going on. please help somebody.
<div class="container">
<p>Add and Delete Items with Total Cost Value</p>
<form>
<div id="tableDiv">
<table id="myTableHead">
<tr>
<th>Item Name</th>
<th>Item Cost</th>
</tr>
<tr>
<td><input type="text" name="ItemName[]" id="ItemName" /></td>
<td><input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="ItemCost" /></td>
</tr>
</table>
<table id="myTable">
</table>
<table id="myTableTot">
<tr>
<td><input type="text" name="Total" value="Total Cost Value --->" readonly /></td>
<td><input type="number" name="TotalValue" id="TotalValue" value=0 readonly /></td>
</tr>
</table>
</div>
<br>
<button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>
</form>
</div>
<script>
function myCreateFunction() {
var TotalCostValueCurrent = parseFloat(document.getElementById("TotalValue").value);
if (TotalCostValueCurrent <= 25000) {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = '<input type="text" name="ItemName[]" id="childItemName" />';
cell2.innerHTML = '<input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="childItemCost" />';
} else {
window.alert("Sorry, You Have Reached Max Shipping Value Limit of 25000, please reduce Pieces to Max Value of 25000");
}
}
function myTotalFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var i = 0;
var itemCostSum = 0;
while (i <= arrLen && itemCostSum <= 25000) {
if (itemCostSum <= 25000) {
itemCostSum = itemCostSum + parseFloat(arrItemCost[i].value);
i++;
document.getElementById("TotalValue").value = Math.ceil(itemCostSum); // Update Total Value
}
}
}
function myDeleteFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var TotalValueCurrent = parseFloat(document.getElementById("TotalValue").value);
var itemCostFinal = 0;
itemCostFinal = TotalValueCurrent - parseInt(arrItemCost[arrLen-1].value);
//FINAL OUTPUT
document.getElementById("myTable").deleteRow(-1); // Delete Last Row
document.getElementById("TotalValue").value = Math.ceil(itemCostFinal); // Final Cost Value
document.getElementById("tableDiv").getElementsByClassName("ItemCostClass").pop(); // Drop last value of Item Array
}
</script>
Inside the form tags buttons tend to do the default action which is submit.
So change your button from,
<button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>
to
<input type="button" onclick="myCreateFunction()" value="Create row">
<input type="button" onclick="myDeleteFunction()" value ="Delete row">
You have to add Input tag instead of button tag. Because button tag in form specifies default submit event on-click so your form submitted when you add any row and also refresh.
<div class="container">
<p>Add and Delete Items with Total Cost Value</p>
<form>
<div id="tableDiv">
<table id="myTableHead">
<tr>
<th>Item Name</th>
<th>Item Cost</th>
</tr>
<tr>
<td><input type="text" name="ItemName[]" id="ItemName" /></td>
<td><input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="ItemCost" /></td>
</tr>
</table>
<table id="myTable">
</table>
<table id="myTableTot">
<tr>
<td><input type="text" name="Total" value="Total Cost Value --->" readonly /></td>
<td><input type="number" name="TotalValue" id="TotalValue" value=0 readonly /></td>
</tr>
</table>
</div>
<br>
<input type="button" onclick="myCreateFunction()" value="Create row" />
<input type="button" onclick="myDeleteFunction()" value="Delete row" />
</form>
</div>
<script>
function myCreateFunction() {
var TotalCostValueCurrent = parseFloat(document.getElementById("TotalValue").value);
if (TotalCostValueCurrent <= 25000) {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = '<input type="text" name="ItemName[]" id="childItemName" />';
cell2.innerHTML = '<input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="childItemCost" />';
} else {
window.alert("Sorry, You Have Reached Max Shipping Value Limit of 25000, please reduce Pieces to Max Value of 25000");
}
}
function myTotalFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var i = 0;
var itemCostSum = 0;
while (i < arrLen && itemCostSum <= 25000) {
if (itemCostSum <= 25000) {
itemCostSum = itemCostSum + parseFloat(arrItemCost[i].value);
i++;
document.getElementById("TotalValue").value = Math.ceil(itemCostSum); // Update Total Value
}
}
}
function myDeleteFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var TotalValueCurrent = parseFloat(document.getElementById("TotalValue").value);
var itemCostFinal = 0;
itemCostFinal = TotalValueCurrent - parseInt(arrItemCost[arrLen-1].value);
//FINAL OUTPUT
document.getElementById("myTable").deleteRow(-1); // Delete Last Row
document.getElementById("TotalValue").value = Math.ceil(itemCostFinal); // Final Cost Value
document.getElementById("tableDiv").getElementsByClassName("ItemCostClass").pop(); // Drop last value of Item Array
}
</script>

add/remove multiple rows using checkbox with javascript

I'm stuck with javascript I working on. I want to add more fields dynamically, my problem is I want to be able to add a row with input boxes. Within the added row, first column contain checkbox, second column contain an increment number, third column contain input txtbox, fourth column checkbox1, fifth column contain input txtbox1 and sixth column contain input txtbox3. Now my question is, how would I add dynamicaly second row under fourth column checkbox1, fifth column txtbox1 and sixth column txtbox3 while maintaing alignment with checkbox,txtbox?
And within the added row, if possible it have to have two button, add row and delete row.
Here is snippet which runs but doesn't do want I expecting:
<HTML>
<HEAD>
<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
<SCRIPT language="javascript">
function addRow(tableID) {
var i=0;
i++;
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);
cell2.innerHTML = rowCount + 0;
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell3.appendChild(element2);
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "checkbox";
element4.name="chkbox[]";
cell4.appendChild(element4);
var cell5 = row.insertCell(4);
cell5.innerHTML = rowCount -1;
var cell6 = row.insertCell(5);
var element5 = document.createElement("input");
element5.type = "text";
element5.name = "txtbox1[]";
cell6.appendChild(element5);
var cell7 = row.insertCell(6);
var element6 = document.createElement("input");
element6.type = "text";
element6.name = "txtbox2[]";
cell7.appendChild(element6);
var cell8 = row.insertCell(7);
var element7 = document.createElement("input");
element7.type = "text";
element7.name = "txtbox3[]";
cell8.appendChild(element7);
}
function addVillageNames()
{
}
function removeVillageNames()
{
}
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>
</HEAD>
<BODY>
<form action="Untitled-2.php" name="Untitled-2" method="post">
<table width="760" id="dataTable" border="1">
<tr>
<TD width="22" rowspan="2"><INPUT type="checkbox" name="chk"/></TD>
<TD width="12" rowspan="2"> 1 </TD>
<TD width="149" rowspan="2"> <INPUT type="text" name="txtbox[]" /> </TD>
<TD width="20"><INPUT type="checkbox" name="chk1"/></TD>
<TD width="12"> 1 </TD>
<TD width="200"> <INPUT type="text" name="txtbox1[]" /></TD>
<TD width="146"> <INPUT type="text" name="txtbox2[]" /> </TD>
<TD width="188"> <INPUT type="text" name="txtbox3[]" /> </TD>
</TR>
<tr>
<TD width="20"> </TD>
<TD width="12"> </TD>
<TD><input type="button" value="Add Row1" onClick="addRow1('dataTable')" /> <input type="button" value="Delete Row1" onClick="deleteRow1('dataTable')" /></TD>
<TD width="146"> </TD>
<TD width="188"> </TD>
</TR>
</TABLE>
<tr>
<td>
<input type="button" value="Add Row" onClick="addRow('dataTable')" />
<input type="button" value="Delete Row" onClick="deleteRow('dataTable')" /> </td></tr>
</form>
</BODY>
</HTML>
As much as I love plain/vanilla javascript, I would have to recommend jQuery for your next project. Here's a jsfiddle of the code using only plain/vanilla javascript.
Here's the JavaScript function you'll need
function hasClass(el, cssClass) {
return el.className && new RegExp("(^|\\s)" + cssClass + "(\\s|$)").test(el.className);
}
var rowNumber = 1;
function addRow(tableID) {
var counter = document.getElementById(tableID).rows.length-1;
var row = document.getElementById(tableID);
var newRow0 = row.rows[1].cloneNode(true);
var newRow1 = row.rows[counter].cloneNode(true);
// Increment
rowNumber ++;
newRow0.getElementsByTagName('td')[1].innerHTML = rowNumber;
// Update the child Names
var items = newRow0.getElementsByTagName("input");
for (var i = 0; i < items.length; i++) {
items[i].value = null;
items[i].name = counter + '_' + items[i].name;
}
var refRow = row.getElementsByTagName('tbody')[0];
refRow.insertBefore(newRow0, refRow.nextSibling);
refRow.insertBefore(newRow1, refRow.nextSibling);
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var i = table.rows.length - 1;
while (2 < i && !hasClass(table.rows[i], 'row-parent')) {
table.deleteRow(i)
i--;
}
if (2 < i) {
table.deleteRow(i)
rowNumber --;
}
}
function addChildRow(e, tableID) {
var table = document.getElementById(tableID);
var newRow = table.rows[0].cloneNode(true);
// Increment
if (e > 0)
if (!isNaN(table.rows[e-1].getElementsByTagName('td')[4].innerHTML))
var counter = parseInt(table.rows[e-1].getElementsByTagName('td')[4].innerHTML)
else
var counter = parseInt(table.rows[e-1].getElementsByTagName('td')[1].innerHTML)
newRow.getElementsByTagName('td')[1].innerHTML = counter + 1;
// Update the child Names
var items = newRow.getElementsByTagName("input");
for (var i = 0; i < items.length; i++) {
items[i].value = null;
items[i].name = counter + '_' + items[i].name;
}
var i = e;
while (1 <= i && !hasClass(table.rows[i], 'row-parent'))
i--;
var parent = table.rows[i].getElementsByTagName('td');
parent[0].rowSpan = counter+2;
parent[1].rowSpan = counter+2;
parent[2].rowSpan = counter+2;
var refRow = table.getElementsByTagName('tr')[e-1];
refRow.parentNode.insertBefore(newRow, refRow.nextSibling);
}
function deleteChildRow(e, tableID) {
var table = document.getElementById(tableID);
var i = e;
while (1 <= i && !hasClass(table.rows[i], 'row-parent'))
i--;
if (e-1 > i)
table.deleteRow(e-1)
}
And here's the HTML
<form action="Untitled-2.php" name="dataTable" method="post">
<table width="760" id="dataTable" border="1">
<tr>
<td width="20">
<input type="checkbox" name="chk1" />
</td>
<td width="12">1</td>
<td width="200">
<input type="text" name="txtbox1[]" />
</td>
<td width="146">
<input type="text" name="txtbox2[]" />
</td>
<td width="188">
<input type="text" name="txtbox3[]" />
</td>
</tr>
<tr class="row-parent">
<td width="22" rowspan="2">
<input type="checkbox" name="chk" />
</td>
<td width="12" rowspan="2">1</td>
<td width="149" rowspan="2">
<input type="text" name="txtbox[]" />
</td>
<td width="20">
<input type="checkbox" name="chk1" />
</td>
<td width="12">1</td>
<td width="200">
<input type="text" name="txtbox1[]" />
</td>
<td width="146">
<input type="text" name="txtbox2[]" />
</td>
<td width="188">
<input type="text" name="txtbox3[]" />
</td>
</tr>
<tr>
<td width="20"> </td>
<td width="12"> </td>
<td>
<input type="button" value="+ Child Row" onClick="addChildRow(this.parentNode.parentNode.rowIndex, 'dataTable')" />
<input type="button" value="- Child Row" onClick="deleteChildRow(this.parentNode.parentNode.rowIndex, 'dataTable')" />
</td>
<td width="146"> </td>
<td width="188"> </td>
</tr>
</table>
<input type="button" value="Add Row" onClick="addRow('dataTable')" />
<input type="button" value="Delete Row" onClick="deleteRow('dataTable')" />
</form>
And here's the CSS to hide the first row:
table tr:first-child {
display: none;
}

Categories