This is my full code. Dynamic rows are generating on add button and deleting on delete icon image. i want to copy the contents of 2 columns from it.
This is my full code. Dynamic rows are generating on add button and deleting on delete icon image. i want to copy the contents of 2 columns from it.
JavaScript Code:
<script type="text/javascript">
var cc = 1;
function addTableRow(jQtable){
var id=cc;
jQtable.each(function() {
var data = "<tr><td class='Arial_4C8966' align='center'><input name='InvoiceDate[]' type='date' class='form-control' placeholder='' style='width:160px' id='InvoiceDate_" + cc + "' size='10' onclick='showData(this.value," + cc + ")'/></td><td class='Arial_4C8966'><input name='Details[]' type='text' class='form-control' style='width:240px' id='Details_" + cc + "' size='10'/></td><td class='Arial_4C8966'><input name='ReceiptNo[]' type='text' class='form-control' style='width:180px' id='ReceiptNo_" + cc + "' size='10' /></td><td class='Arial_4C8966'><input name='Amount[]' class='form-control' style='width:180px' type='text' onblur='copy_data(this);' id='Amount_" + cc + "' size='10' /></td><td class='Arial_4C8966'><input name='Total[]' style='width:180px' class='form-control' type='text' id='Total_" + cc + "' size='10' /></td><td class='Arial_4C8966'><img src='assets/img/pictures.png' style='cursor:pointer; border:0px; width:16px;' onclick='setDeletedID("+ cc +");$(this).parent().parent().remove();' />
var $table = $(this);
var n = $('tr:last td', this).length;
var tds = data;
cc++;
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
}
function setDeletedID(itemID){
objReceiptNo=document.getElementById('ReceiptNo_'+itemID)
if(objReceiptNo.value!=''){
if(document.getElementById('txtDeletedIDs').value==''){
document.getElementById('txtDeletedIDs').value= objReceiptNo.value;
}else{
document.getElementById('txtDeletedIDs').value+= ', '+objReceiptNo.value;
}
}
}
</script>
HTML CODE:
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="dynamicInput">
<tr class="Form_Text_Label">
<td align="center">INVOICE DATE*</td>
<td align="center">DETAILS*</td>
<td align="center">RECEIPT NO*</td>
<td align="center">AMOUNT*</td>
<td align="center">TOTAL*</td>
<td align="center"></td>
</tr>
</table>
</div>
</div>
<div class="col-sm-6">
<input type="button" value="Add" class="frmBtns" onclick="addTableRow($('#dynamicInput'));"
onblur="copy_data(this);" style="font-family: Calibri; font-size: 15px;">
<br>
</div>
Please take a look at revised HTML and JS code. Hope it will work for you:
var cc = 1;
CalculateGrandTotal();
function addTableRow(jQtable){
var id=cc;
jQtable.each(function() {
var data = "<tr><td class='Arial_4C8966' align='center'><input name='InvoiceDate[]' type='date' class='form-control' placeholder='' style='width:160px' id='InvoiceDate_" + cc + "' size='10' onclick='showData(this.value," + cc + ")'/></td><td class='Arial_4C8966'><input name='Details[]' type='text' class='form-control' style='width:240px' id='Details_" + cc + "' size='10'/></td><td class='Arial_4C8966'><input name='ReceiptNo[]' type='text' class='form-control' style='width:180px' id='ReceiptNo_" + cc + "' size='10' /></td><td class='Arial_4C8966'><input name='Amount[]' class='form-control' style='width:180px' type='text' onblur='copy_data(this);' id='Amount_" + cc + "' size='10' /></td><td class='Arial_4C8966'><input name='Total[]' style='width:180px' class='form-control Total' type='text' id='Total_" + cc + "' size='10' /></td><td class='Arial_4C8966'><img src='assets/img/pictures.png' style='cursor:pointer; border:0px; width:16px;' onclick='setDeletedID("+ cc +");$(this).parent().parent().remove();' />";
var $table = $(this);
var n = $('tr:last td', this).length;
var tds = data;
cc++;
if ($('tbody', this).length > 0) {
$('tbody', this).append(tds);
} else {
$(this).append(tds);
}
});
}
function copy_data(obj){
var current = $(obj);
var currentTr = current.closest("tr");
var currentTotalElem = currentTr.find(".Total");
currentTotalElem.val(current.val());
CalculateGrandTotal();
}
//calculate the grand total
function CalculateGrandTotal(){
var grandTotal = 0;
$(".Total").each(function(){
var currVal = $(this).val();
if(!isNaN(currVal))
{
grandTotal += parseFloat(currVal);
}
});
$("#grand_total").val(grandTotal);
}
function setDeletedID(itemID){
objReceiptNo=document.getElementById('ReceiptNo_'+itemID)
if(objReceiptNo.value!=''){
if(document.getElementById('txtDeletedIDs').value==''){
document.getElementById('txtDeletedIDs').value= objReceiptNo.value;
}else{
document.getElementById('txtDeletedIDs').value+= ', '+objReceiptNo.value;
}
}
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="dynamicInput">
<tr class="Form_Text_Label">
<td align="center">INVOICE DATE*</td>
<td align="center">DETAILS*</td>
<td align="center">RECEIPT NO*</td>
<td align="center">AMOUNT*</td>
<td align="center">TOTAL*</td>
<td align="center"></td>
</tr>
</table>
</div>
</div>
<div class="col-sm-6">
<input type="button" value="Add" class="frmBtns" onclick="addTableRow($('#dynamicInput'));"
style="font-family: Calibri; font-size: 15px;"></input>
<br>
<label class="col-sm-3 text-right ">Grand Total :</label> <div class="col-sm-3"> <td class="Arial_4C8966"><input name="grand_total" type="text" class="form-control" id="grand_total" size="10" />
</div>
Please try to use above JS and HTML code as it is. Replace your corresponding code with above one. Please note: your function setDeletedID doesn't work as provided HTML don't contain any element with an id txtDeletedIDs. Please check that again. Thanks.
Related
I write code of html and javascript in which when i click on button it add a new row.It is working fine now i have to find total by multiplying quantity and cost.It works for first row but if i add more rows it not work
<table class="table table-bordered table-striped">
<thead>
<th>#</th>
<th>Item Name</th>
<th>Batch No</th>
<th>Remarks</th>
<th>Quantity</th>
<th>Cost Per Piece</th>
<th>Total</th>
<th>Action</th>
</thead>
<tbody id="tbody">
</tbody>
<center><button type="button" name="" onclick="additem()" class="btn btn-success"> Add</button></center></td>
and javascript code is
function additem() {
x++;
var html="<tr";
html += "<td><center>"+x+"</center></td>";
html += "<td><input type='text' class='form-control' name='product_name'></td>";
html += "<td><input type='text' class='form-control' name='batch_no'></td>";
html += "<td><input type='text' class='form-control' name='remarks'></td>";
html += "<td><input type='number' class='form-control' oninput='calculate()' id='qty' name='total_qty'></td>";
html += "<td><input type='number' class='form-control' oninput='calculate()' id='cost' name='cost'></td>";
html += "<td><input type='number' class='form-control' id='total' name='total' readonly></td>";
html += "<td><button type='button' id='btn' class='btn btn-danger'><i class='fa fa-remove'></i></button></td>";
html += "</tr>";
document.getElementById("tbody").insertRow().innerHTML= html;
}
You can set a dynamic id on these inputs using x variable:
Check out this jsfiddle link
let x = 0;
function additem() {
x++;
var html=`<tr;
<td><center>${x}</center></td>
<td><input type='text' class='form-control' name='product_name'></td>
<td><input type='text' class='form-control' name='batch_no'></td>
<td><input type='text' class='form-control' name='remarks'></td>
<td><input id='qty${x}' type='number' class='form-control' oninput='calculate(${x})' id='qty' name='total_qty'></td>
<td><input id='cost${x}' type='number' class='form-control' oninput='calculate(${x})' id='cost' name='cost'></td>
<td><input type='number' class='form-control' id='total${x}' name='total' readonly></td>
<td><button type='button' id='btn' class='btn btn-danger'><i class='fa fa-remove'></i></button></td>
</tr>`;
document.getElementById("tbody").insertRow().innerHTML= html;
}
function calculate(x) {
const qty = document.getElementById(`qty${x}`).value;
const cost = document.getElementById(`cost${x}`).value;
const totalElem = document.getElementById(`total${x}`);
totalElem.value = qty * cost
}
You need to create a unique id for each row and get the element by unique Id. Something like this.
let x = 0;
function additem() {
x++;
var html = "<tr";
html += "<td><center>" + x + "</center></td>";
html += "<td><input type='text' class='form-control' name='product_name'></td>";
html += "<td><input type='text' class='form-control' name='batch_no'></td>";
html += "<td><input type='text' class='form-control' name='remarks'></td>";
html += "<td><input id='qty_" + x + "' type='number' class='form-control' oninput='calculate(" + x + ")' id='qty' name='total_qty'></td>";
html += "<td><input id='cost_" + x + "' type='number' class='form-control' oninput='calculate(" + x + ")' id='cost' name='cost'></td>";
html += "<td><input id='total_" + x + "' type='number' class='form-control' id='total' name='total' readonly></td>";
html += "<td><button type='button' id='btn' class='btn btn-danger'><i class='fa fa-remove'></i></button></td>";
html += "</tr>";
document.getElementById("tbody").insertRow().innerHTML = html;
}
function calculate(x) {
let qty;
let cost
if (document.getElementById('qty_' + x))
qty = document.getElementById('qty_' + x).value;
if (document.getElementById('cost_' + x))
cost = document.getElementById('cost_' + x).value;
let total = qty * cost;
if (document.getElementById('total_' + x))
document.getElementById('total_' + x).value = total;
}
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>
I have created a table and I want to add the data below the table but data is being added at the top,
I have written a search property when user enters the product id the data should be shown and can't figure out where my code went wrong,
I want to add serch field to all the buttons should I write the code many times is there any solution?
$(document).ready(function() {
var url = "http://34.201.147.118:3001/getAllData";
$.getJSON(url, function(data) {
console.log(data);
//console.log("AllData")
var obj = data['AllData'];
//console.log(obj)
for (var i = 0; i < obj.length; i++) {
var tr = "<tr>" +
"<td>" + obj[i]["ProductID"] + "</td>" +
"<td>" + obj[i]["Title"] + "</td>" +
$("#mytable").append('<tr class="child"> tr</tr>');
}
});
});
function goodCall() {
$(document).ready(function() {
$("#id").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#myTable tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
}
body {
background-image: url("banner.jpg");
background-size: 100%;
}
#mytable {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
width: 100%;
}
#mytable td,
#customers th {
border: 1px solid #ddd;
padding: 8px;
}
#mytable tr:hover {
background-color: #ddd;
}
#mytable th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Page Content -->
<div style="margin-left:25%">
<h1 style="color:white;">TITLE DETAILS</h1>
<div class="w3-container" id="add">
<div class="" style="color:white;">
<form name="test_form" id="101">
<table class="table borderless">
<tr>
<th>Title Identifier</th>
</tr>
<tr>
<td style="border:none">
<b>PRODUCT ID</b>
<br>
<input type="text" id="id" style="color:black;" required></td>
<td style="border:none"></td>
<td style="border:none">
<b>PRODUCT TITLE</b>
<br><input type="text" id="title" style="color:black;" required></td>
</tr>
<tr>
<td style="border:none">
<br> <b>director </b>
<br> <input type="text" id="ter" style="color:black;" required>
</td>
<td style="border:none"></td>
<td style="border:none">
<b>producer</b>
<br> <input type="text" id="media" style="color:black;" required>
</td>
</tr>
</table>
</form>
<input type="button" onclick="goodCall()" value="Search" style="color:Red;">
<table id='mytable'>
<tr>
<th>ID</th>
<th>PRODUCTTITLE</th>
</tr>
<div>
<br><br>
</div>
</table>
</div>
</div>
</div>
Here you have a basic functional example https://jsfiddle.net/0Lvqcd8t/39/
You should change this:
var tr = "<tr>" +
"<td>" + obj[i]["ProductID"] + "</td>" +
"<td>" + obj[i]["Title"] + "</td>" +
$("#mytable").append('<tr class="child"> tr</tr>');
for this:
var tr = "<td>" + obj[i]["ProductID"] + "</td>" +
"<td>" + obj[i]["Title"] + "</td>" +
$("#mytable").append('<tr class="child">'+ tr+'</tr>');
In the first case you are creating <tr><tr class="child><td></td></tr> (first <tr> is wrong) and browser will render something like <tr>tr</tr><tr class='child'>empty</tr> also, tr var in first example is not interpreted as variable, so you should place it like +tr+. I've made a basic filter function at the end that works with id.
I have an HTML table that adds a new row below where the button in current row is located. Currently when the row is created it generates a clone of the row above including the data. I would like this to be a row that has no entry for the input values rather than a clone of the values above.
Javascript
function addRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i+1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
tr.children[0].innerHTML = tr.parentNode.querySelectorALL("tr").length-1;
}
<table id="Table" border="1">
<tr>
<td><b>Measured Depth</b></td>
<td><b>Inclination</b></td>
<td><b>Azimuth</b></td>
<td><b>Delete?</b></td>
<td><b>Add Row?</b></td>
</tr>
<tr>
<td><input size=25 type="text" id="Measured Depth0[]" contenteditable="true" value='339'></td>
<td><input size=25 type="text" id="Inclination0[]" contenteditable='true' value='0.540000021'></td>
<td><input size=25 type="text" id="Azimuth0[]" contenteditable='true' value='310.7200012'></td>
<td><input type="button" id="delbutton0" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmorebutton0" value="Add Row Below" onclick="addRow(this)"/></td>
</tr>
</table>
after you add a row, you can just set the values of all inputs in that row to "". get all the inputs of type text using tr.querySelectorAll("input[type='text']") and using a loop set values of all to ""
function addRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i+1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
var inputs = tr.querySelectorAll("input[type='text']");
for(var i=0; i<inputs.length; i++)
inputs[i].value = "";
}
<table id="Table" border="1">
<tr>
<td><b>Measured Depth</b></td>
<td><b>Inclination</b></td>
<td><b>Azimuth</b></td>
<td><b>Delete?</b></td>
<td><b>Add Row?</b></td>
</tr>
<tr>
<td><input size=25 type="text" id="Measured Depth0[]" contenteditable="true" value='339'></td>
<td><input size=25 type="text" id="Inclination0[]" contenteditable='true' value='0.540000021'></td>
<td><input size=25 type="text" id="Azimuth0[]" contenteditable='true' value='310.7200012'></td>
<td><input type="button" id="delbutton0" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmorebutton0" value="Add Row Below" onclick="addRow(this)"/></td>
</tr>
</table>
You can do this very easily with jQuery:
var $lastRow = $("table#Table tr:last-child");
var $newRow = $lastRow.clone()
$newRow.find("input[type=text]").val(''); //empty all the values in text inputs
$("table#Table").append( $newRow );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="Table" border="1">
<tr>
<td><b>Measured Depth</b></td>
<td><b>Inclination</b></td>
<td><b>Azimuth</b></td>
<td><b>Delete?</b></td>
<td><b>Add Row?</b></td>
</tr>
<tr>
<td><input size=25 type="text" id="Measured Depth0[]" contenteditable="true" value='339'></td>
<td><input size=25 type="text" id="Inclination0[]" contenteditable='true' value='0.540000021'></td>
<td><input size=25 type="text" id="Azimuth0[]" contenteditable='true' value='310.7200012'></td>
<td><input type="button" id="delbutton0" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmorebutton0" value="Add Row Below" onclick="addRow(this)"/></td>
</tr>
</table>
Add this line of code to your function to empty values in HTML code:
function addRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
var tr = document.getElementById('Table').insertRow(i+1);
tr.innerHTML = row.parentNode.parentNode.innerHTML;
tr.innerHTML = tr.innerHTML.replace(/value='.*'/, "value=''"); //this will remove all values from your html
tr.children[0].innerHTML = tr.parentNode.querySelectorALL("tr").length-1;
}
Using JQuery:
function addRow(){
var t = $("#Table tr").last().clone();
t.find("input").each(function(i,element) {
$(element).val("");
});
t.appendTo("#Table");
}
I can suggest you do this - define table rows in javascript and add those directly. Also, use th for table headers
function edit_row(no) {
document.getElementById("edit_button" + no).style.display = "none";
document.getElementById("save_button" + no).style.display = "block";
// get elements
var measured = document.getElementById("measured_row" + no);
var inclination = document.getElementById("inclination_row" + no);
var azimuth = document.getElementById("azimuth_row" + no);
// get their values
var measured_data = measured.innerHTML;
var inclination_data = inclination.innerHTML;
var azimuth_data = azimuth.innerHTML;
// replace by editable input tags
measured.innerHTML = "<input type='text' id='measured_text" + no + "' value='" + measured_data + "'>";
inclination.innerHTML = "<input type='text' id='inclination_text" + no + "' value='" + inclination_data + "'>";
azimuth.innerHTML = "<input type='text' id='azimuth_text" + no + "' value='" + azimuth_data + "'>";
}
function save_row(no) {
// same as in edit function
var measured_val = document.getElementById("measured_text" + no).value;
var inclination_val = document.getElementById("inclination_text" + no).value;
var azimuth_val = document.getElementById("azimuth_text" + no).value;
document.getElementById("measured_row" + no).innerHTML = measured_val;
document.getElementById("inclination_row" + no).innerHTML = inclination_val;
document.getElementById("azimuth_row" + no).innerHTML = azimuth_val;
document.getElementById("edit_button" + no).style.display = "block";
document.getElementById("save_button" + no).style.display = "none";
}
function delete_row(no) {
document.getElementById("row" + no + "").outerHTML = "";
}
function add_row() {
var new_measured = document.getElementById("new_measured").value;
var new_inclination = document.getElementById("new_inclination").value;
var new_azimuth = document.getElementById("new_azimuth").value;
var table = document.getElementById("data_table");
var table_len = (table.rows.length) - 1;
var row = table.insertRow(table_len).outerHTML = "<tr id='row" + table_len + "'><td id='measured_row" + table_len + "'>" + new_measured + "</td><td id='inclination_row" + table_len + "'>" + new_inclination + "</td><td id='azimuth_row" + table_len + "'>" + new_azimuth + "</td><td><input type='button' id='edit_button" + table_len + "' value='Edit' class='edit' onclick='edit_row(" + table_len + ")'> <input type='button' id='save_button" + table_len + "' value='Save' class='save' onclick='save_row(" + table_len + ")'> <input type='button' value='Delete' class='delete' onclick='delete_row(" + table_len + ")'></td></tr>";
document.getElementById("new_measured").value = "";
document.getElementById("new_inclination").value = "";
document.getElementById("new_azimuth").value = "";
}
<table align='center' cellspacing=2 cellpadding=5 id="data_table" border=1>
<tr>
<th>Measured Depth</th>
<th>Inclination</th>
<th>Azimuth</th>
</tr>
<tr id="row1">
<td id="measured_row1">339</td>
<td id="inclination_row1">0.540000021</td>
<td id="azimuth_row1">310.7200012</td>
<td>
<input type="button" id="edit_button1" value="Edit" class="edit" onclick="edit_row('1')">
<input type="button" id="save_button1" value="Save" class="save" onclick="save_row('1')">
<input type="button" value="Delete" class="delete" onclick="delete_row('1')">
</td>
</tr>
<tr>
<td><input type="text" id="new_measured"></td>
<td><input type="text" id="new_inclination"></td>
<td><input type="text" id="new_azimuth"></td>
<td><input type="button" class="add" onclick="add_row();" value="Add Row"></td>
</tr>
</table>
Now there is an input from add more button, the user writes some number and than he gets the sum, I am trying to get the sum automatically. its didnt work but I need the output print in text box.... for this code
here my javascript :
var i = $('table tr').length;
var count = $('table tr').length;
var row = i;
var a = 0;
for (a = 0; a <= i; a++) {
$(".addmore_" + a).on('click', function (a) {
return function() {
var box = $("#box_"+ a);
box.val( Number(box.val())+1 );
var data = "<td><input class='form-control sedang' type='text' id='packinglist_" + a + "' name='packinglist"+ a +"[]'/></td>";
$("#keatas_" + a).append(data);
};
}
(a));
//this calculates values automatically
calculateSum();
$("#packinglist_"+a).on("keydown keyup", function() {
calculateSum();
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$("#packinglist_"+ a).each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
$(this).css("background-color", "#FEFFB0");
}
else if (this.value.length != 0){
$(this).css("background-color", "red");
}
});
$("input#netto_"+ a).val(sum.toFixed(2));
}
}
here my html :
if($_GET['mod'] == 'Buat Surat Jalan Keluar'){
function romanNumerals($num)
{
$n = intval($num);
$res = '';
/*** roman_numerals array ***/
$roman_numerals = array(
'M' => 1000,
'CM' => 900,
'D' => 500,
'CD' => 400,
'C' => 100,
'XC' => 90,
'L' => 50,
'XL' => 40,
'X' => 10,
'IX' => 9,
'V' => 5,
'IV' => 4,
'I' => 1);
foreach ($roman_numerals as $roman => $number)
{
/*** divide to get matches ***/
$matches = intval($n / $number);
/*** assign the roman char * $matches ***/
$res .= str_repeat($roman, $matches);
/*** substract from the number ***/
$n = $n % $number;
}
/*** return the res ***/
return $res;
}
echo"</div>";
echo"
<link rel='stylesheet' type='text/css' href='css/jquery-ui.min.css' />
<link rel='stylesheet' type='text/css' href='css/main.css' />
";
$month = date('n');
$b=romanNumerals($month);
$years=date('Y');
echo"<div class='form-group'>";
$tanggal=date('d');
$s=mysql_query("SELECT * FROM surat_jalan WHERE identitas_surat = 1 AND bulantahun=$_POST[bulantahun] ORDER BY no_surat_jalan ASC");
while($a=mysql_fetch_array($s)){
$nomor = $a[2];
$potong = (int)substr($nomor,0,3);
$potong++;
}
$kosong= mysql_num_rows($s);
if(count($kosong) == 0){
$nomore = sprintf('%03s',1);
}
else {
$nomore = sprintf('%03s',$potong);
}
echo"
<body>
<form id='students' method='post' name='students' action='../Action/tambah.php?mod=suratkeluar&batas=$_POST[jumlahdata]' autocomplete='off'>
<div class='row '>
<div class='col-lg-4 '>
<div class='panel panel-default noborder'>
<div class='panel-body '>
<h3>No : ".$nomore."/$b/$years</h3>
<input class='form-control' type='hidden' id='nosurat' name='nosurat' value='".$nomore."/$b/$years' />
</div>
</div>
</div>
<div class='col-lg-4 text-center'>
<div class='panel panel-default'>
<div class='panel-body'>
<label>Customer</label><select name='customer' class= 'form-control '>
";
$s=mysql_query('SELECT * FROM customer ORDER BY nama_customer ASC');
while($ben=mysql_fetch_array($s)){
echo"<option value='$ben[id_customer]_$ben[nama_customer]_$ben[alamat_customer]'>$ben[nama_customer]</option>";
}
echo" </select>
</div>
</div>
</div>
<div class='col-lg-4 text-center'>
<div class='panel panel-default'>
<div class='panel-body'>
<label>Nomor PO</label><select name='nopo' class= 'form-control '>
<option value='0_-'> - </option>
";
$s=mysql_query('SELECT * FROM preorder WHERE pabrik = 0 and nonview = 0 GROUP BY no_po ORDER BY no_po ASC');
while($ben=mysql_fetch_array($s)){
echo"<option value='$ben[id_po]_$ben[no_po]'>$ben[no_po]</option>";
}
echo" </select>
</div>
</div>
</div>
<div class='table-responsive'>
<table class='table table-bordered'>
<tr>
<th>No</th>
<th>Jenis Benang</th>
<th>Warna</th>
<th>Lot</th>
<th>Netto</th>
<th>Box</th>
<th>Cones</th>
<th>Keterangan</th>
</tr>";
$s=mysql_query("SELECT * FROM surat_jalan order by id_surat DESC");
$a=mysql_fetch_array($s);
for($i=1;$i<=$_POST['jumlahdata'];$i++)
{
$nomor = $a[0];
$iden = $nomor + $i;
echo" <tr>
<td><span id='snum'>$i.</span></td>
<input class='form-control' type='hidden' id='hiddenlot_$i' name='hiddenlot[]' />
<input class='form-control' type='hidden' id='hiddencustomer_$i' name='hiddencustomer[]' />
<input class='form-control' type='hidden' id='hiddenprice_$i' name='hiddenprice[]' />
<td><input class='form-control' type='text' id='jenisbenang_$i' name='jenisbenang[]' readonly/></td>
<td><input class='form-control' type='text' id='warna_$i' name='warna[]' readonly/></td>
<td><input class='form-control' type='text' id='lot_$i' name='lot[]' required/></td>
<td><input class='form-control sedang' type='text' id='netto_$i' name='netto[]' required/> </td>
<td><input class='form-control pendek' type='text' id='box_$i' name='box[]' /> </td>
<td><input class='form-control pendek' type='text' id='cones_$i' name='cones[]'/> </td>
<td><input class='form-control' type='text' id='keterangan_$i' name='keterangan[]'/>
<input class='form-control' type='hidden' id='keterangan_$i' name='identitas[]' value='$iden'/>
</td>
</tr>
<tr>
<td><a><span class='glyphicon glyphicon-plus addmore_$i' id='$i'></span></a><br>
<a><span class='glyphicon glyphicon-minus delete_$i'></a> </td>
<td colspan='10'>
<table id='keatas_$i' class='keatas'>
<tr>
</tr>
</table>
</tr>
</td>";
}
echo"
</table>
<div class='form-group'>
<button type='submit' class='btn btn-primary btn-lg btn-block' name='submit'>Tambah Data</button>
</div>
</div>
</form>
</body>
</div>
</div>
</div>
</div><!-- /container -->
}
so my code didnt work on it , but anything else working properly
any response would be appreciated
I have check your code. i have made some changes in your code. You have to use , in your jQuery code. Here is change "keydown, keyup" .
Also change in $('body').on('click', ".addmore_" + a, function (a) { in your for loop. and $('body').on("keydown, keyup", "#packinglist_"+a, function() {
This is because you are creating dynamic input
Please check this , it should work :
var i = $('table tr').length;
var count = $('table tr').length;
var row = i;
var a = 0;
for (a = 0; a <= i; a++) {
$(".addmore_" + a).on('click', function (a) {
return function() {
var box = $("#box_"+ a);
box.val( Number(box.val())+1 );
var data = "<td><input class='form-control sedang' type='text' id='packinglist_" + a + "' name='packinglist"+ a +"[]'/></td>";
$("#keatas_" + a).append(data);
};
}
(a));
//this calculates values automatically
calculateSum();
$("#packinglist_"+a).on("keydown keyup", function() {
calculateSum();
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$("#packinglist_"+ a).each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
$(this).css("background-color", "#FEFFB0");
}
else if (this.value.length != 0){
$(this).css("background-color", "red");
}
});
$("input#netto_"+ a).val(sum.toFixed(2));
}
}
HTML code updates :
if($_GET['mod'] == 'Buat Surat Jalan Keluar'){
function romanNumerals($num)
{
$n = intval($num);
$res = '';
/*** roman_numerals array ***/
$roman_numerals = array(
'M' => 1000,
'CM' => 900,
'D' => 500,
'CD' => 400,
'C' => 100,
'XC' => 90,
'L' => 50,
'XL' => 40,
'X' => 10,
'IX' => 9,
'V' => 5,
'IV' => 4,
'I' => 1);
foreach ($roman_numerals as $roman => $number)
{
/*** divide to get matches ***/
$matches = intval($n / $number);
/*** assign the roman char * $matches ***/
$res .= str_repeat($roman, $matches);
/*** substract from the number ***/
$n = $n % $number;
}
/*** return the res ***/
return $res;
}
echo"</div>";
echo"
<link rel='stylesheet' type='text/css' href='css/jquery-ui.min.css' />
<link rel='stylesheet' type='text/css' href='css/main.css' />
";
$month = date('n');
$b=romanNumerals($month);
$years=date('Y');
echo"<div class='form-group'>";
$tanggal=date('d');
$s=mysql_query("SELECT * FROM surat_jalan WHERE identitas_surat = 1 AND bulantahun=$_POST[bulantahun] ORDER BY no_surat_jalan ASC");
while($a=mysql_fetch_array($s)){
$nomor = $a[2];
$potong = (int)substr($nomor,0,3);
$potong++;
}
$kosong= mysql_num_rows($s);
if(count($kosong) == 0){
$nomore = sprintf('%03s',1);
}
else {
$nomore = sprintf('%03s',$potong);
}
echo"
<body>
<form id='students' method='post' name='students' action='../Action/tambah.php?mod=suratkeluar&batas=$_POST[jumlahdata]' autocomplete='off'>
<div class='row '>
<div class='col-lg-4 '>
<div class='panel panel-default noborder'>
<div class='panel-body '>
<h3>No : ".$nomore."/$b/$years</h3>
<input class='form-control' type='hidden' id='nosurat' name='nosurat' value='".$nomore."/$b/$years' />
</div>
</div>
</div>
<div class='col-lg-4 text-center'>
<div class='panel panel-default'>
<div class='panel-body'>
<label>Customer</label><select name='customer' class= 'form-control '>
";
$s=mysql_query('SELECT * FROM customer ORDER BY nama_customer ASC');
while($ben=mysql_fetch_array($s)){
echo"<option value='$ben[id_customer]_$ben[nama_customer]_$ben[alamat_customer]'>$ben[nama_customer]</option>";
}
echo" </select>
</div>
</div>
</div>
<div class='col-lg-4 text-center'>
<div class='panel panel-default'>
<div class='panel-body'>
<label>Nomor PO</label><select name='nopo' class= 'form-control '>
<option value='0_-'> - </option>
";
$s=mysql_query('SELECT * FROM preorder WHERE pabrik = 0 and nonview = 0 GROUP BY no_po ORDER BY no_po ASC');
while($ben=mysql_fetch_array($s)){
echo"<option value='$ben[id_po]_$ben[no_po]'>$ben[no_po]</option>";
}
echo" </select>
</div>
</div>
</div>
<div class='table-responsive'>
<table class='table table-bordered'>
<tr>
<th>No</th>
<th>Jenis Benang</th>
<th>Warna</th>
<th>Lot</th>
<th>Netto</th>
<th>Box</th>
<th>Cones</th>
<th>Keterangan</th>
</tr>";
$s=mysql_query("SELECT * FROM surat_jalan order by id_surat DESC");
$a=mysql_fetch_array($s);
for($i=1;$i<=$_POST['jumlahdata'];$i++)
{
$nomor = $a[0];
$iden = $nomor + $i;
echo" <tr>
<td><span id='snum'>$i.</span></td>
<input class='form-control' type='hidden' id='hiddenlot_$i' name='hiddenlot[]' />
<input class='form-control' type='hidden' id='hiddencustomer_$i' name='hiddencustomer[]' />
<input class='form-control' type='hidden' id='hiddenprice_$i' name='hiddenprice[]' />
<td><input class='form-control' type='text' id='jenisbenang_$i' name='jenisbenang[]' readonly/></td>
<td><input class='form-control' type='text' id='warna_$i' name='warna[]' readonly/></td>
<td><input class='form-control' type='text' id='lot_$i' name='lot[]' required/></td>
<td><input class='form-control sedang' type='text' id='netto_$i' name='netto[]' required/> </td>
<td><input class='form-control pendek' type='text' id='box_$i' name='box[]' /> </td>
<td><input class='form-control pendek' type='text' id='cones_$i' name='cones[]'/> </td>
<td><input class='form-control' type='text' id='keterangan_$i' name='keterangan[]'/>
<input class='form-control' type='hidden' id='keterangan_$i' name='identitas[]' value='$iden'/>
</td>
</tr>
<tr>
<td><a><span class='glyphicon glyphicon-plus addmore_$i' id='$i'></span></a><br>
<a><span class='glyphicon glyphicon-minus delete_$i'></a> </td>
<td colspan='10'>
<table id='keatas_$i' class='keatas'>
<tr>
</tr>
</table>
</tr>
</td>";
}
echo"
</table>
<div class='form-group'>
<button type='submit' class='btn btn-primary btn-lg btn-block' name='submit'>Tambah Data</button>
</div>
</div>
</form>
</body>
</div>
</div>
</div>
</div><!-- /container -->";
}