prevent added tables from disappearing when page is refreshed - javascript

basically, when user entered some values in each added rows, those values and the number of added rows don't disappear... how is that possible?
here's my code:
function delPlace(row) {
var txtb = document.getElementById('travel');
var len = txtb.rows.length;
if (len > 2) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('travel').deleteRow(i);
} else {
alert("Can't delete all rows. One row must at least remain.");
}
}
function addPlace() {
var txtb = document.getElementById('travel');
var add_row = txtb.rows[1].cloneNode(true);
var len = txtb.rows.length;
add_row.cells[0].innerHTML = len;
var inp = add_row.cells[1].getElementsByTagName('input')[0];
inp.id += len;
inp.value = '';
txtb.appendChild(add_row);
}
<table id="travel">
<p> List the countries/cities the person had traveled to/from in the past 15 days before diagnosis </p>
<tr><input type="button" id="add_place" value="Add" onclick="addPlace()" /></tr>
<tr>
<td style="display:none"></td>
<td>
<input type="text" class="form-control" name="travel_history[]" value="" placeholder="Enter text here..."
style="width:500px">
</td>
<td>
<input type="button" id="del_place" value="Remove" onclick="delPlace(this)" />
</td>
</tr>
</table>
</div>

Related

Reset the HTML table on change

I am working on expense management with pouchdb
The data is inserted into the database based on date
i want to reset to original table if there is no data in date onchange
Above picture is with data on particular date
if i change the date the table is not reset to original table
this picture is when changing the date the table is not resetting
only head row and one row is hard coded extra rows or dynamically created on click add row button
//add row
function addRow(no_of_rows){
for (let i = 0; i < no_of_rows; i++){
console.log(i)
var root = document.getElementById('customers').getElementsByTagName('tbody')[0];
var rows = root.getElementsByTagName('tr');
var clone = cloneEl(rows[rows.length - 1]);
cleanUpInputs(clone);
root.appendChild(clone);
function cloneEl(el) {
var clo = el.cloneNode(true);
return clo;
}
function cleanUpInputs(obj) {
for (var i = 0; n = obj.childNodes[i]; ++i) {
if (n.childNodes && n.tagName != 'INPUT') {
cleanUpInputs(n);
} else if (n.tagName == 'INPUT') {
n.value = '';
}
}
}
}
}
// getting data from pouchdb
function getAccounts(){
var getdate = document.getElementById('Expdate').value;
var table = document.getElementById('customers');
db.get(getdate, function(err, doc) {
if (err) {
//want to handle the table reset here
} else {
console.log(doc);
addRow(doc['DailyAccount'].length -1);
for (let i = 0; i < doc['DailyAccount'].length; i++){
// console.log(i);
table.rows[i+1].cells[0].firstChild.value = doc.DailyAccount[i]['Description'];
table.rows[i+1].cells[1].firstChild.value = doc.DailyAccount[i]['Investment'];
table.rows[i+1].cells[2].firstChild.value = doc.DailyAccount[i]['Expenses'];
}
document.getElementById("investtotal").value = doc.TotalInvestment;
document.getElementById("exptotal").value = doc.TotalExpenses;
}
});
}
<input type="date" name="Date" id="Expdate" onchange="getAccounts()" >
<button onclick="addRow(1)"><i class="fa fa-plus" aria-hidden="true"></i>Add Row</button>
<button onclick="DeleteRow()"><i class="fa fa-minus" aria-hidden="true"></i>Delete Row</button>
<table id="customers">
<tbody id="mytbody">
<tr>
<th>Descritption</th>
<th>Investment</th>
<th>Expenses</th>
</tr>
<tr>
<td><input type="text" name="yourname" /> </td>
<td onchange="getinvest()"><input type="number" name="yourname" /></td>
<td onchange="getexpense()"><input type="number" name="yourname" /></td>
</tr>
</tbody>
</table>
<label for="fname">Investment Total : </label>
<input type="number" name="Investtotal" id="investtotal">
<label for="fname">Expense Total : </label>
<input type="number" name="Exptotal" id="exptotal">
<input type="button" id="save" value ="save" name="save" onclick="day()">
structure of pouchdb doc
var Accountdoc = {
_id: getdate,
TotalInvestment:Totalinvest,
TotalExpenses: Totalexp,
DailyAccount: Accounts,// accounts is array of object
};

Using JavaScript to add new row to table but how to I set the variables to be unique if I clone?

I have a button that the user clicks on to add a new row to the bottom of an input table. I would like this to also increment the id. So the next row would have desc2, hours2, rate2 and amount2 as the id. Is there a way to do this in the JavaScript function.
Also - just want to check my logic on this. After the user completes the filled out form, I will be writing all the data to a mysql database on two different tables. Is this the best way to go about this? I want the user to be able to add as many lines in the desc_table as they need. If this is the correct way to be going about this, what is the best way to determine how many lines they have added so I can insert into the db table using a while loop?
JS file:
function new_line() {
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
}
HTML:
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
<td></td>
</tr>
<tr>
<td ><textarea name="description" id="desc1" ></textarea></td>
<td> <input type="text" name="hours" id="hours1" ></td>
<td> <input type="text" name="rate" id="rate1"></td>
<td><input type="text" name="amount" id="amount1"></td>
<td>
<button type="button" name="add_btn" onclick="new_line(this)">+</button>
<button type="button" name="delete_btn" onclick="delete_row(this)">x</button>
</td>
</tr>
</table>
Thank you!
Check this code.After appending the row it counts the number of rows and and then assigns via if condition and incremental procedure the id's:
function new_line() {
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
for(var i=1;i<rows.length;i++){
if(rows[i].children["0"].children["0"].id.match((/desc/g))){
rows[i].children["0"].children["0"].id='desc'+i;
}
if(rows[i].children["1"].children["0"].id.match((/hours/g))){
rows[i].children["1"].children["0"].id='hours'+i;
}
if(rows[i].children["2"].children["0"].id.match((/rate/g))){
rows[i].children["2"].children["0"].id='rate'+i;
}
if(rows[i].children["3"].children["0"].id.match((/amount/g))){
rows[i].children["3"].children["0"].id='amount'+i;
}
}
}
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
<td></td>
</tr>
<tr>
<td ><textarea name="description" id="desc1" ></textarea></td>
<td> <input type="text" name="hours" id="hours1" ></td>
<td> <input type="text" name="rate" id="rate1"></td>
<td><input type="text" name="amount" id="amount1"></td>
<td>
<button type="button" name="add_btn" onclick="new_line(this)">+</button>
<button type="button" name="delete_btn" onclick="delete_row(this)">x</button>
</td>
</tr>
</table>
Please change variable names for more descriptive. :)
Example solution...
https://jsfiddle.net/Platonow/07ckv5u7/1/
function new_line() {
var table = document.getElementById("desc_table");
var rows = table.getElementsByTagName("tr");
var row = rows[rows.length - 1];
var newRow = rows[rows.length - 1].cloneNode(true);
var inputs = newRow.getElementsByTagName("input");
for(let i=0; i<inputs.length; i++) {
inputs[i].id = inputs[i].name + rows.length;
}
var textarea = newRow.getElementsByTagName("textarea")[0];
textarea.id = textarea.name + rows.length;
table.appendChild(newRow);
}
Note that I removed/edited below fragment.
x.style.display = "";
r.parentNode.insertBefore(x, r);
You could do this a lot easier with jquery or another dom manipulation language, but with vanilla JS here's an example of simply looping through the new row's inputs & textarea and incrementing a counter to append.
var count = 1;
function new_line() {
count++;
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
// update input ids
var newInputs = Array.from(x.getElementsByTagName('input'))
.concat(Array.from(x.getElementsByTagName('textarea')));
newInputs.forEach(function(input) {
var id = input.getAttribute('id').replace(/[0-9].*/, '');
input.setAttribute('id', id + count);
});
}
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
<td></td>
</tr>
<tr>
<td ><textarea name="description" id="desc1" ></textarea></td>
<td> <input type="text" name="hours" id="hours1" ></td>
<td> <input type="text" name="rate" id="rate1"></td>
<td><input type="text" name="amount" id="amount1"></td>
<td>
<button type="button" name="add_btn" onclick="new_line(this)">+</button>
<button type="button" name="delete_btn" onclick="delete_row(this)">x</button>
</td>
</tr>
</table>

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>

Increment my input text id when table row is cloned using Javascript

I am having a table it contains only one row. Row has a lot of elements like textboxs and buttons. When I click the button the table row will be cloned using append() function. My problem is when I click the button I want to increment the textbox and button id. How can I do this?
Example HTML:
<tr id="items:1">
<td id="id">
<input type="text" id="price:1" name="price" value="" size="6" readonly="readonly" />
</td>
<td id="id">
<input type="text" id="quantity:1" name="quantity" size="10" align="middle" onblur="totalprice(this)" />
</td>
<td id="id">
<input type="text" id="total:1" name="total" size="10" value="0" readonly="readonly" align="middle" />
</td>
<td id="id">
<input type="button" onclick="cloneRow()" id="button:1" value="ADD" />
</td>
</tr>
Example JavaScript:
function cloneRow() {
var row = document.getElementById("items:1");
var table = document.getElementById("particulars");
var clone = row.cloneNode(true);
var rowId = "items:" + a.toString();
clone.id = rowId;
var tabledataid = document.getElementById("id");
var inputtext = tabledataid.getElementsByTagName("input");
var inputtextid = inputtext[a];
var changeInputTextid = "price:" + b.toString();
inputtextid.id = changeInputTextid;
alert(changeInputTextid);
table.appendChild(clone);
a++;
}
A fiddle
Create a function to add rows and just use the indexes of text boxes and columns correctly
function insertRow() {
var x = document.getElementById('ttable');
var new_row = x.rows[0].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].innerHTML = len;
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
x.appendChild(new_row);
}

submit two form contents onto one action page

i have two Forms to be submitted to a single destination page.
<form name= "form1" id="form1" action="final.php">
<input type="box1" name="box1" value="" >
</form>
<form name ="form2" id="form2" action="final.php">
<table>
<input type ="text" id="txt_1" name ="txt_1" value="">
...
</table>
</form>
<input type= "button" name="mybutton" id="mybutton" onclick="somefunction();">
here ,
form1 has some satic contents
and
form2 has a table which is dynamically generated by js...
problem is ...i want to submitted values from both the forms to same page final.php ...how cud i do it .....pls avoid jquery/ajax...
simple javascript welcomed ...
thanks in advance !
this is the js for generating dynamic table in form2
<script type="text/javascript">
function viewsource() {
alert(document.body.innerHTML);
}
</script>
<script type="text/javascript">
function addRowToTable()
{
var tbl = document.getElementById('tblSample');
var frm=document.form2;
if (!frm.ary) frm.ary=[frm.t1_1,frm.t1_2,frm.t1_3];
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
// numberd row
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
// Item row
var cellRight1 = row.insertCell(1);
var el1 = document.createElement('input');
frm.ary.push(el1);
el1.type = 'text';
el1.value = '';
el1.name = 't' + iteration + '_1';
el1.id = 't' + iteration + '_1';
el1.size = 13;
el1.onkeyup=Calc;
el1.onblur=Calc;
cellRight1.appendChild(el1);
// Price row
var cellRight2 = row.insertCell(2);
var el2 = document.createElement('input');
frm.ary.push(el2);
el2.type = 'text';
el2.value = '';
el2.name = 't' + iteration + '_2';
el2.id = 't' + iteration + '_2';
el2.size = 10;
el2.onkeyup=Calc;
el2.onblur=Calc;
cellRight2.appendChild(el2);
// Price row
var cellRight3 = row.insertCell(3);
var el3 = document.createElement('input');
frm.ary.push(el3);
el3.type = 'text';
el3.value = '0';
el3.name = 't' + iteration + '_3';
el3.id = 't' + iteration + '_3';
el3.size = 10;
cellRight3.appendChild(el3);
}
function removeRowFromTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
if (lastRow > 3) tbl.deleteRow(lastRow - 1);
}
function formReset()
{
document.getElementById("form2").reset();
}
</script>
<script type="text/javascript">
function Calc(){
var frm=document.form2;
if (!frm.ary){ frm.ary=[frm.t1_1,frm.t1_2,frm.t1_3];}
for (var zxc0=0;zxc0<frm.ary.length;zxc0+=3)
{
var total =1;
if (frm.ary[zxc0].value.length>0&&!isNaN(frm.ary[zxc0].value))
{
total =frm.ary[zxc0].value*1* frm.ary[zxc0+1].value;
}
frm.ary[zxc0+2].value =total;
}
var sum1 =0;
for (var zxd0=0;zxd0<frm.ary.length;zxd0+=3)
{
if (frm.ary[zxd0+2].value.length>0&&!isNaN(frm.ary[zxd0+2].value))
{
sum1 +=parseInt(frm.ary[zxd0+2].value);
}
}
frm.sum.value = sum1;
}
</script>
<form action="final.php" method="post" name="form2" id="form2">
<imput type ="text" name ="temp" id="temp" >
<table border="2" border-color="#000000" border-type="solid" id="tblSample"
align="center" font-size="20">
<tr>
<th>
<input type="button" value="Add " onclick="addRowToTable();"></th><th>
<input type="button" value="Remove " onclick="removeRowFromTable();" /></th>
<th> <input type="button" value="Reset" onclick="formReset();">
</th>
</tr><br>
<tr id="cloneid" >
<td>
1.
</td>
<td>
<input type="text" name="t1_1" id="t1_1" size="16" value="0" onkeyup="Calc();"
onblur="Calc();">
</td>
<td>
<input type="text" name="t1_2" id="t1_2" size="16" value="0" onkeyup="Calc();"
onblur="Calc();">
</td>
<td>
<input type="text" name="t1_3" id="t1_3" value= "0" size="16">
</td>
</tr>
</table>
<table border="2" border-color="#000000" align="center">
<tr>
<td colspan="3" align="center">
Sum: <input type="text" name="sum" id="sum">
</td>
</tr>
</table>
</form>
<input type="button" name = "mybutton" id ="mybutton" value="set"
onclick="somefunction();">
}
and
form1 is same as mentioned including jquery for datetimepickers along witha couple of text boxes...
u can use Java Script
function button1click() {
yourForm.action = "Final.php";
yourForm.submit();
}
n in HTML
<form action='' method='post'>
..
</form>

Categories