Dynamically created table row with input fields not posted - javascript

I have this form with a table inside, I dynamically add rows with input fields to the table, but the problem is that when I submit the form i get an error saying undefined index.
Here's the code:
HTML
`
<div class="row">
<div class="col-md-12">
<table id="myTable">
<th>
ID number
</th>
<th>
Lastname
</th>
<th>
Firstname
</th>
<th>
M.I.
</th>
<th>Course
</th>
<th>
Address
</th>
<th>
Contact number
</th>
<tr>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default btn-sm" data-dismiss="modal" value="Cancel"/>
<input type="submit" class="btn btn-primary btn-sm" id="btn_add_adv" name="btn_add_mul" value="Save"/>
</div>
</form>
`
JAVASCRIPT creates the rows
function insertRow()
{
var table = document.getElementById('myTable');
var len = table.rows.length;
var row = table.insertRow(len);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
var cell7 = row.insertCell(6);
var el1 = document.createElement("input");
el1.type = "text";
el1.name = "idnum[]";
el1.size = "8";
cell1.appendChild(el1);
var el2 = document.createElement("input");
el2.type = "text";
el2.name = "lname[]";
cell2.appendChild(el2);
var el3 = document.createElement("input");
el3.type = "text";
el3.name = "fname[]";
cell3.appendChild(el3);
var el4 = document.createElement("input");
el4.type = "text";
el4.name = "mname[]";
el4.size = "1";
cell4.appendChild(el4);
var el5 = document.createElement("input");
el5.type = "text";
el5.name = "course[]";
el5.size = "5";
cell5.appendChild(el5);
var el6 = document.createElement("input");
el6.type = "text";
el6.name = "add[]";
cell6.appendChild(el6);
var el7 = document.createElement("input");
el7.type = "text";
el7.name = "contact[]";
el7.size = "12";
cell7.appendChild(el7);
}
PHP collects the values from the created input fields
<?php
if(isset($_POST['btn_add_mul'])){
$id = $_POST['idnum'];
$lastname = $_POST['lname'];
$firstname = $_POST['fname'];
$midname = $_POST['mname'];
$course = $_POST['course'];
$address = $_POST['add'];
$contact = $_POST['contact'];
for($i = 0, $count = count($id); $i < $count; $i++ )
{
$id_num = $id[$i];
$lname = $lastname[$i];
$fname = $firstname[$i];
$mname = $midname[$i];
$cou = $course[$i];
$add = $address[$i];
$con = $contact[$i];
mysql_query("insert into tblstudent(id,lname,fname,mname,contact,address,course)Values('$id','$lname','$fname','$mname','$con','$add','$course')") or die(mysql_error());
}
}
?>
Is there something wrong with how i created the rows?

function insertRow()
{
var table = document.getElementById('myTable');
var len = table.rows.length;
var row = table.insertRow(len);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
var cell7 = row.insertCell(6);
var el1 = document.createElement("input");
el1.type = "text";
el1.name = "idnum[]";
el1.size = "8";
cell1.appendChild(el1);
var el2 = document.createElement("input");
el2.type = "text";
el2.name = "lname[]";
cell2.appendChild(el2);
var el3 = document.createElement("input");
el3.type = "text";
el3.name = "fname[]";
cell3.appendChild(el3);
var el4 = document.createElement("input");
el4.type = "text";
el4.name = "mname[]";
el4.size = "1";
cell4.appendChild(el4);
var el5 = document.createElement("input");
el5.type = "text";
el5.name = "course[]";
el5.size = "5";
cell5.appendChild(el5);
var el6 = document.createElement("input");
el6.type = "text";
el6.name = "add[]";
cell6.appendChild(el6);
var el7 = document.createElement("input");
el7.type = "text";
el7.name = "contact[]";
el7.size = "12";
cell7.appendChild(el7);
}
insertRow()
<form method="post">
<div class="row">
<div class="col-md-12">
<table id="myTable">
<th>
ID number
</th>
<th>
Lastname
</th>
<th>
Firstname
</th>
<th>
M.I.
</th>
<th>Course
</th>
<th>
Address
</th>
<th>
Contact number
</th>
<tr>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default btn-sm" data-dismiss="modal" value="Cancel"/>
<input type="submit" class="btn btn-primary btn-sm" id="btn_add_adv" name="btn_add_mul" value="Save"/>
</div>
</form>
<?php if (isset($_POST['btn_add_mul'])) {
$id = $_POST['idnum'];
$lastname = $_POST['lname'];
$firstname = $_POST['fname'];
$midname = $_POST['mname'];
$course = $_POST['course'];
$address = $_POST['add'];
$contact = $_POST['contact'];
for ($i = 0, $count = count($id); $i < $count; $i++) {
$id_num = $id[$i];
$lname = $lastname[$i];
$fname = $firstname[$i];
$mname = $midname[$i];
$cou = $course[$i];
$add = $address[$i];
$con = $contact[$i];
mysql_query("insert into tblstudent(id,lname,fname,mname,contact,address,course)Values('$id','$lname','$fname','$mname','$con','$add','$course')") or die(mysql_error());
}
}?>
First open form tag and set its method to post and you will see data is posting in below format and you need to insert json_encode data in db not direct array it will throw an error.
Array
(
[idnum] => Array
(
[0] => sada
)
[lname] => Array
(
[0] => sad
)
[fname] => Array
(
[0] => Zsdad
)
[mname] => Array
(
[0] => sdsad
)
[course] => Array
(
[0] => sd
)
[add] => Array
(
[0] => asda
)
[contact] => Array
(
[0] => ada
)
[btn_add_mul] => Save
)

Related

Need help updating the index for selected row

I have been stuck on an issue where I am trying to use Javascript to add and remove a row from a table.
I got the add part working, the delete somewhat. The delete fails if you delete the first row or a row in the middle (live code can be seen here
I uploaded its code on PasteBin
<script type="text/javascript">
var itemNumber = 0
var currentRow = 0;
var selectedRow = 0;
function theIndex(theRow){
selectedRow = theRow;
}
document.getElementById("addItem").addEventListener("click", function(){
if (document.getElementById('whatToDo').value != ""){
currentRow++;
var table = document.getElementById('myList');
var row = table.insertRow(currentRow);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
itemNumber++;
// alert(currentRow);
// cell1.innerHTML = itemNumber;
cell2.innerHTML = document.getElementById('whatToDo').value;
cell3.innerHTML = document.getElementById('whenToDo').value;
cell4.innerHTML = document.getElementById('whereToDo').value;
row.addEventListener('click', theIndex.bind(null, currentRow));
document.getElementById('whatToDo').value = "";
document.getElementById('whenToDo').value = "";
document.getElementById('whereToDo').value = "";
}
});
document.getElementById("removeItem").addEventListener("click", function(){
// var theRow = document.getElementById('whatToMark').value;
var theRow = selectedRow;
alert("index: " +theRow + " elements: " + currentRow);
if (theRow > 0){
document.getElementById("myList").deleteRow(theRow);
document.getElementById('whatToMark').value = "";
currentRow--;
itemNumber--;
}
selectedRow = 0;
});
document.getElementById("markAsDone").addEventListener("click", function(){
// var theRow = document.getElementById('whatToMark').value;
var theRow = selectedRow;
alert("index: " +theRow + " elements: " + currentRow);
var table = document.getElementById('myList');
if (theRow != 0){
table.rows[theRow].style.setProperty("text-decoration", "line-through");
document.getElementById('whatToMark').value = "";
}
selectedRow = 0;
});
</script>
I am learning Javascript and wanted to do more than the exercise that was being given by adding new features to it.
Your approach to mark the current selected row has some issues:
row.addEventListener('click', theIndex.bind(null, currentRow));
Instead of using a global variable I suggest to use a row attribute (or class). Hence, change that line to:
row.addEventListener('click', function(e) {
document.querySelectorAll('tr[selected]').forEach(function(item) {
item.removeAttr('selected');
})
row.setAttribute('selected', true);
});
Add the attribute selected for the current row and remove the same attribute for other rows.
In this way, when you need to get the current selected row you can simply:
var rSelected = document.querySelector('tr[selected]');
var theRow = (rSelected == null) ? 0 : rSelected.rowIndex;
var itemNumber = 0
var currentRow = 0;
var selectedRow = 0;
function theIndex(theRow) {
selectedRow = theRow;
}
document.getElementById("addItem").addEventListener("click", function () {
if (document.getElementById('whatToDo').value != "") {
currentRow++;
var table = document.getElementById('myList');
var row = table.insertRow(currentRow);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
itemNumber++;
// alert(currentRow);
// cell1.innerHTML = itemNumber;
cell2.innerHTML = document.getElementById('whatToDo').value;
cell3.innerHTML = document.getElementById('whenToDo').value;
cell4.innerHTML = document.getElementById('whereToDo').value;
//row.addEventListener('click', theIndex.bind(null, currentRow));
row.addEventListener('click', function(e) {
document.querySelectorAll('tr[selected]').forEach(function(item) {
item.removeAttr('selected');
})
row.setAttribute('selected', true);
});
document.getElementById('whatToDo').value = "";
document.getElementById('whenToDo').value = "";
document.getElementById('whereToDo').value = "";
}
});
document.getElementById("removeItem").addEventListener("click", function () {
// var theRow = document.getElementById('whatToMark').value;
var rSelected = document.querySelector('tr[selected]');
var theRow = (rSelected == null) ? 0 : rSelected.rowIndex;
if (theRow > 0) {
document.getElementById("myList").deleteRow(theRow);
//document.getElementById('whatToMark').value = "";
currentRow--;
itemNumber--;
}
selectedRow = 0;
});
document.getElementById("markAsDone").addEventListener("click", function () {
// var theRow = document.getElementById('whatToMark').value;
var theRow = selectedRow;
alert("index: " + theRow + " elements: " + currentRow);
var table = document.getElementById('myList');
if (theRow != 0) {
table.rows[theRow].style.setProperty("text-decoration", "line-through");
document.getElementById('whatToMark').value = "";
}
selectedRow = 0;
});
<div class="container">
<div class="row">
<div class="col-lg-4 col-sm-6">
<table class="table table-hover">
<tr>
<td colspan="3">
<h1>To Do List Example</h1>
</td>
</tr>
<tr>
<th><label>Item</label></th>
<th><label>Date</label></th>
<th><label>Location</label></th>
</tr>
<tr>
<td>
<input type="text" id="whatToDo" value="">
</td>
<td>
<input type="date" id="whenToDo" value="">
</td>
<td>
<input type="text" id="whereToDo" value="">
</td>
</tr>
<tr>
<td>
<button id="addItem" class="btn btn-default btn-primary active">
<i class="fas fa-plus"></i> Add This Item
</button>
</td>
<td>
<button id="markAsDone" class="btn btn-default ">
<i class="fas fa-check"></i> Mark As Done
</button>
</td>
<td>
<button id="removeItem" class="btn btn-default">
<i class="fas fa-trash-alt"></i> Remove Item
</button>
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="col-lg-4 col-sm-6">
<table class="table table-hover" id="myList">
<tr>
<th><label></label></th>
<th><label>Event</label></th>
<th><label>Date</label></th>
<th><label>Location</label></th>
</tr>
</table>
</div>
</div>
</div>
This line is throwing a null value error:
document.getElementById('whatToMark').value = "";
Neither in your JS, nor in your HTML, do you ever set an element to the ID of whatToMark.

Add function not working

I wrote below the javascript which will allow user to add and delete the row and calculate the weighting. The addition and deletion are working fine but I believe I am unable to do sum of weighting. Can you please advise ?
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "txtbox[]";
cell3.appendChild(element3);
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "txtbox[]";
element4.class = "wtotal1";
cell4.appendChild(element4);
}
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);
}
}
function weighttotal1(){
var tweight1 = 0;
var cusid_ele = document.getElementsByClassName('wtotal1');
for (var i = 0; i < cusid_ele.length; ++i) {
if (!isNaN(parseFloat(cusid_ele[i].textContent)) )
tweight1 += parseFloat(cusid_ele[i].textContent);
}
document.getElementById('tweight1').value=tweight1;
}
<table id="dataTable1" class="table table-condensed table-hover table-responsive table-striped table-bordered">
<tbody>
<tr>
<th></th>
<th>ComponentId</th>
<th>Component Description</th>
<th>Weighting</th>
</tr>
</tbody>
</table>
<br>
<div class="col-sm-6">
<div class="form-inline">
<input class="form-control input-sm" name="tweight" type="text" id="tweight1" value="" readonly>
<button onclick="weighttotal1()">Weigthing total</button>
</div>
</div>
Two things:
1.- Replaces the attribute
element4.class = "wtotal1"; By element4.className = "wtotal1";
2 replaces the cusid_ele[i].textContent attribute with cusid_ele[i].value
The complet code
<script>
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "txtbox[]";
cell3.appendChild(element3);
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "txtbox[]";
element4.className = "wtotal1";
cell4.appendChild(element4);
}
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);
}
}
function weighttotal1(){
var tweight1 = 0;
var cusid_ele = document.getElementsByClassName('wtotal1');
for (var i = 0; i < cusid_ele.length; ++i) {
if (!isNaN(parseFloat(cusid_ele[i].value)) )
tweight1 += parseFloat(cusid_ele[i].value);
}
document.getElementById('tweight1').value=tweight1;
}
</script>
<table id="dataTable1" class="table table-condensed table-hover table-responsive table-striped table-bordered">
<tbody>
<tr>
<th></th>
<th>ComponentId</th>
<th>Component Description</th>
<th>Weighting</th>
</tr>
</tbody>
</table>
<br>
<div class="col-sm-6">
<div class="form-inline">
<button onclick="addRow('dataTable1')">Add Row</button><button
onclick="deleteRow('dataTable1')">Delete Row</button>
<br>
<br>
<input class="form-control input-sm" name="tweight" type="text" id="tweight1" value="" readonly>
<button onclick="weighttotal1()">Weigthing total</button>
</div>
</div>

How to update multiple values in JavaScript

First off, I'm sorry for my poor English.
I'm making information system for school and have a problem when I update data for student. There are siblings fields on student form. They can add one or more siblings (one to many relationship). The program has been successfully to adding siblings into databases (there are two databases, student (id [auto increment - primary key], student_id name, sex, age, ..., etc) and siblings (id (primary key), student_id, siblings_name, siblings_age, ..., etc).
But, the program has been failed when I update siblings data.
ADD SIBLINGS
php:
<table id='siblingsTable'>
<a href='javascript:void(0);' onclick='addRow()'><img src='../images/add.png'/></a>
<a href='javascript:void(0);' onclick='deleteRow()'><img src='../images/delete.png'/></a><br />
<th>Name</th>
<th>Age</th>
<th></th>
</table>
js:
<script>
function addRow() {
var table = document.getElementById("siblingsTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.name = "siblings_name[]";
element1.value = "";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "siblings_age[]";
element2.value = "";
cell2.appendChild(element2);
}
function deleteRow() {
var table = document.getElementById("siblingsTable");
var rowCount = table.rows.length;
table.deleteRow(rowCount -1);
}
</script>
saving to database:
if (!empty($_POST['siblings_name']) && !empty($_POST['siblings_age']) && is_array($_POST['siblings_name']) && is_array($_POST['siblings_age']) && count($_POST['siblings_name']) === count($_POST['siblings_age'])) {
$auth_array = $_POST['auth_key'];
$name_array = $_POST['siblings_name'];
$age_array = $_POST['siblings_age'];
for ($i = 0; $i < count($name_array); $i++) {
$auth = mysql_real_escape_string($auth_array);
$name = mysql_real_escape_string($name_array[$i]);
$age = mysql_real_escape_string($age_array[$i]);
mysql_query("INSERT INTO skkk_web_siblings (auth_key, siblings_name, siblings_age) VALUES ('$auth', '$name', '$age')");
}
}
This is my problem when i want to updating data:
$sib = mysql_query("SELECT COUNT(auth_key) FROM skkk_web_siblings WHERE auth_key = '$_GET[id]'");
$totalsiblings = mysql_result($sib,0);
...
$siblings = mysql_query("SELECT * FROM skkk_web_siblings WHERE auth_key = '$_GET[id]'");
while($row = mysql_fetch_array($siblings)){
$id = $row['id'];
$name = $row['siblings_name'];
$age = $row['siblings_age'];
$siblingsname[] = $name;
$siblingsage[] = $age;
}
...
...
...
<table id='siblingsTable'>
<a href='javascript:void(0);' onclick='editRow()'><img src='../images/edit.png'/></a><br />
<th>Name</th>
<th>Age</th>
</table>
...
<script>
function editRow() {
var table = document.getElementById("siblingsTable");
var total = '<?php echo $totalsiblings; ?>';
var name = jQuery.parseJSON('<?php echo json_encode($siblingsname); ?>');
var age = jQuery.parseJSON('<?php echo json_encode($siblingsage); ?>');
var i;
var table = '';
for (i = 0; i < total; i++) {
tbl += '<input type="text" name="siblings_name[]" value="' + name[i] + '"/>';
tbl += '<input type="text" name="siblings_age[]" value="' + age[i] + '"/>';
}
document.getElementById("siblingsTable").innerHTML = table;
}
</script>
...
//updating to database
if (!empty($_POST['siblings_name']) && !empty($_POST['siblings_age']) && is_array($_POST['siblings_name']) && is_array($_POST['siblings_age']) && count($_POST['siblings_name']) === count($_POST['siblings_age'])) {
$name_array = $_POST['siblings_name'];
$age_array = $_POST['siblings_age'];
for ($i = 0; $i < count($name_array); $i++) {
$name = mysql_real_escape_string($name_array[$i]);
$age = mysql_real_escape_string($age_array[$i]);
mysql_query("UPDATE skkk_web_siblings SET siblings_name = '$name', siblings_age = '$age' WHERE auth_key = '$_POST[id]'");
}
}
When I update one name, it changes all siblings name. What should I do?
Thanks for your help.

Form within table contains dynamically created input parameters that are not being passed in IE 9 and 10

var i = 0;
var a = 3;
function addNewAnswer(tableID) {
var table = document.getElementById(tableID);
if(i < 10)
{
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
cell1.innerHTML = '<font size="2" face="Courier New"><b>Enter Answer ' + String.fromCharCode(67+i) + ':</b></font>';
var cell2 = row.insertCell(1);
var element1 = document.createElement("input");
element1.size = 40;
element1.type = "text";
element1.name = "answer"+a;
cell2.appendChild(element1);
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "radio";
element2.name = "radios";
element2.value = String.fromCharCode(67+i);
cell3.appendChild(element2);
i++;
a++;
}
}
My HTML Form:
<table>
<tr>
<form method=post name="submitform" action="verify-qedit.jsp">
<td>
<form method=post name="submitform" action="verify-qedit.jsp">
<table id="dataTable">
<tr>
<th colspan="3" align="left">Question</th>
</tr>
</table>
</form>
</td>
</form>
</tr>
</table>
When I submit the form, I only can retrieve the parameters not created by the above javascript. It only works in compatibility mode - IE 8 standards and below. Please help because I have spent days trying to find out before posting this question.
Does this work on all the browsers you are targetting?
http://jsfiddle.net/4nbB5/1
function addNewAnswer(tableID) {
var rowCount, row, cell1, cell2, cell3, element1, element2, char;
var i = 0;
var table = document.getElementById(tableID);
while (i < 10) {
rowCount = table.rows.length;
row = table.insertRow(rowCount);
cell1 = row.insertCell(0);
char = String.fromCharCode(65 + i);
cell1.innerHTML = '<font size="2" face="Courier New"><b>Enter Answer ' + char + ':</b></font>';
cell2 = row.insertCell(1);
element1 = document.createElement("input");
element1.size = 40;
element1.type = "text";
element1.name = "answer" + i;
cell2.appendChild(element1);
cell3 = row.insertCell(2);
element2 = document.createElement("input");
element2.type = "radio";
element2.name = "radios";
element2.value = char;
cell3.appendChild(element2);
i++;
}
}
addNewAnswer('foo');
All I did was remove 'a', and declare 'i', change 'if' to while, changed 67 in fromCharCode to 65.. Looked to be what you may have wanted at some point so I stopped.
The problem had nothing to do with the javascript. It was because I was putting the form tag in the wrong place within the table after the tr tag instead of after the td tag.
<table>
<tr>
<td>
<form method=post name="submitform" action="verify-qedit.jsp">
<table id="dataTable">
<tr>
<th colspan="3" align="left">Question</th>
</tr>
</table>
</form>
</td>
</tr>
</table>

Calculate the Price automatically in invoice

I am making an invoice system, I want to get the price textbox to be automatically calculated. I am having a table of random rows, in the invoice. How do I do it via a JS function on price text box.
var rowCount = 0;
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "chk[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount;
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "item[]";
element2.required = "required";
cell3.appendChild(element2);
var cell4 = row.insertCell(3);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "qty[]";
cell4.appendChild(element3);
var cell5 = row.insertCell(4);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "cost[]";
cell5.appendChild(element4);
var cell5 = row.insertCell(4);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "price[]";
cell5.appendChild(element4);
}
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);
}
}
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<form action="" method="post" enctype="multipart/form-data">
invoice:
<INPUT type="text" name="invoice id" />
<TABLE id="dataTable" width="350px" border="1" style="border-collapse:collapse;">
<TR>
<TH>Select</TH>
<TH>Sr. No.</TH>
<TH>Item</TH>
<TH>Cost</TH>
<TH>Qty</TH>
<TH formula="cost*qty" summary="sum">Price</TH>
</TR>
<TR>
<TD>
<INPUT type="checkbox" name="chk[]" />
</TD>
<TD> 1 </TD>
<TD>
<INPUT type="text" name="item[] " /> </TD>
<TD>
<INPUT type="text" name="qty[]" /> </TD>
<TD>
<INPUT type="text" name="cost[]" /> </TD>
<TD>
<INPUT type="text" name="price[]" /> </TD>
</TR>
</TABLE>
<input type="submit" />
</form>
Update anno 2022
const container = document.getElementById("container")
const table = document.querySelector("#dataTable tbody");
const totalField = document.getElementById("total");
const addRow = () => {
const newRow = table.firstElementChild.cloneNode(true);
newRow.querySelectorAll("input").forEach(inp => inp.type === "checkbox" ? inp.checked = false : inp.value = "")
table.appendChild(newRow)
newRow.querySelectorAll("td")[1].textContent = table.querySelectorAll("tr").length;
};
const removeRow = () => {
table.querySelectorAll("[type=checkbox]:checked").forEach(chk => chk.closest("tr").remove())
table.querySelectorAll("tr td:nth-child(2)").forEach((cell, i) => cell.textContent = i + 1);
totalIt();
};
const totalIt = (e) => {
if (e && e.target.matches("[type=checkbox]")) return;
const qtyFields = [...document.getElementsByName("qty[]")];
let total = qtyFields.map(qtyField => {
const parent = qtyField.closest("tr");
const qty = +qtyField.value;
const cost = +parent.querySelector(".cost").value;
const priceField = parent.querySelector(".price");
let price = cost * qty;
if (isNaN(price)) price = 0;
priceField.value = price.toFixed(2);
return price;
}).reduce((a, b) => a + b)
totalField.value = total ? total.toFixed(2) : "0.00";
};
container.addEventListener("click", function(e) {
const tgt = e.target;
if (!tgt.id) return;
if (tgt.id === "add") addRow();
else if (tgt.id === "remove") removeRow();
})
container.addEventListener("input", totalIt);
#dataTable {
width: 350px;
margin: 5px;
}
#dataTable tr,
td,
th {
border: 1px solid black;
border-collapse: collapse;
}
<div id="container">
<input type="button" value="Add Row" id="add" />
<input type="button" value="Delete checked Rows" id="remove" />
<form action="" method="post" enctype="multipart/form-data">
invoice:<input type="text" name="invoice id" />
<table id="dataTable">
<thead>
<tr>
<th>Select</th>
<th>Sr. No.</th>
<th>Item</th>
<th>Qty</th>
<th>Cost</th>
<th formula="cost*qty" summary="sum">Price</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" name="chk[]" /></td>
<td>1</td>
<td><input type="text" name="item[] " /></td>
<td><input type="text" class="qty" name="qty[]" /></td>
<td><input type="text" class="cost" name="cost[]" /></td>
<td><input type="text" class="price" name="price[]" /></td>
</tr>
</tbody>
</table>
total: <input type="text" readonly="readonly" id="total" /><br />
<input type="submit" />
</form>
Old answer
DEMO
You had cost and QTY in the wrong cells according to the header cell!!!
<TD> <INPUT type="text" id="qty1" name="qty[]"/> </TD>
<TD> <INPUT type="text" id="cost1" name="cost[]" /> </TD>
<TD> <INPUT type="text" id="price1" name="price[]" /> </TD>
New code:
function calc(idx) {
var price = parseFloat(document.getElementById("cost"+idx).value)*
parseFloat(document.getElementById("qty"+idx).value);
// alert(idx+":"+price);
document.getElementById("price"+idx).value= isNaN(price)?"0.00":price.toFixed(2)
}
window.onload=function() {
document.getElementsByName("qty[]")[0].onkeyup=function() {calc(1)};
document.getElementsByName("cost[]")[0].onkeyup=function() {calc(1)};
}
var rowCount =0;
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "chk[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount;
var cell3 = row.insertCell(2);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "item[]";
element3.required = "required";
cell3.appendChild(element3);
var cell4 = row.insertCell(3);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "qty[]";
element4.id = "qty"+rowCount;
element4.onkeyup=function() {calc(rowCount);}
cell4.appendChild(element4);
var cell5 = row.insertCell(4);
var element5 = document.createElement("input");
element5.type = "text";
element5.name = "cost[]";
element5.id = "cost"+rowCount;
element5.onkeyup=function() {calc(rowCount);}
cell5.appendChild(element5);
var cell6 = row.insertCell(5);
var element6 = document.createElement("input");
element6.type = "text";
element6.name = "price[]";
element6.id = "price"+rowCount
cell6.appendChild(element6);
}
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);
}
}
Here is a total - you can actually replace calc with this if you cut and paste calc into where I do calc(i)
function totalIt() {
var qtys = document.getElementsByName("qty[]");
var total=0;
for (var i=1;i<=qtys.length;i++) {
calc(i);
var price = parseFloat(document.getElementById("price"+i).value);
total += isNaN(price)?0:price;
}
document.getElementById("total").value=isNaN(total)?"0.00":total.toFixed(2);
}
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<form action="" method="post" enctype="multipart/form-data">
invoice:<INPUT type="text" name="invoice id"/>
<TABLE id="dataTable" width="350px" border="1" style="border-collapse:collapse;">
<TR>
<TH>Select</TH>
<TH>Sr. No.</TH>
<TH>Item</TH>
<TH>Cost</TH>
<TH>Qty</TH>
<TH formula="cost*qty"summary="sum">Price</TH>
</TR>
</TABLE>
<input type="submit" />
And script:
<SCRIPT language="javascript">
var rowCount =0;
function calculatePrice(qtyElement, costElement, priceElement) {
priceElement.value = qtyElement.value * costElement.value;
}
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "chk[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount;
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "item[]";
element2.required = "required";
cell3.appendChild(element2);
var cell4 = row.insertCell(3);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "qty[]";
element3.onchange = function(){
calculatePrice(this, this.parentElement.parentElement.childNodes[4].childNodes[0], this.parentElement.parentElement.childNodes[5].childNodes[0]);
};
cell4.appendChild(element3);
var cell5 = row.insertCell(4);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "cost[]";
element4.onchange = function(){
calculatePrice(this.parentElement.parentElement.childNodes[3].childNodes[0], this, this.parentElement.parentElement.childNodes[5].childNodes[0]);
};
cell5.appendChild(element4);
var cell6 = row.insertCell(5);
var element5 = document.createElement("input");
element5.type = "text";
element5.name = "price[]";
cell6.appendChild(element5);
}
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);
}
}
addRow('dataTable');
</SCRIPT>
Just bind the calculation to, for example, a key event. You should create the first invoice row also via JS.
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name = "chk[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount;
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "item[]";
element2.required = "required";
cell3.appendChild(element2);
var cell4 = row.insertCell(3);
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "qty[]";
cell4.appendChild(element3);
var cell5 = row.insertCell(4);
var element4 = document.createElement("input");
element4.type = "text";
element4.name = "cost[]";
cell5.appendChild(element4);
var cell5 = row.insertCell(5);
var element5 = document.createElement("input");
element5.type = "text";
element5.name = "price[]";
cell5.appendChild(element5);
var calcPrice = function() {
try {
element5.value = element3.value * element4.value;
} catch(e) {
}
}
element3.onkeyup = calcPrice;
element4.onkeyup = calcPrice;
}
You may implement the calculations inside a function that is called when the onchange event is fired in some of the input fields (the last of a row or the first of the next row calculates the previuos row price).
<script type="text/javascript">
$(function(){
//add new row
$('.add').click(function(){
var tr = '<tr>'+
'<td><input type="text" name="product_name[]" class="form-control product_name"></td>'+
'<td><input type="text" name="quantity[]" class="form-control quantity"></td>'+
'<td><input type="text" name="price[]" class="form-control price"></td>'+
'<td><input type="text" name="amount[]" class="form-control amount"></td>'+
'<td><input type="button" class="btn btn-danger remove" value="Remove"></td>'+
'</tr>';
$('.details').append(tr);
});
// end
// total amount
$('.details').delegate('.quantity,.price','keyup',function(){
var tr = $(this).parent().parent();
var price = tr.find('.price').val();
var qty = tr.find('.quantity').val();
var amount = price * qty;
tr.find('.amount').val(amount);
total();
});
// end
// delete row
$('.details').delegate('.remove','click',function(){
var con = confirm("Do you want to remove it ?");
if(con)
{
$(this).parent().parent().remove();
total();
}
});
// end
//get pay
$('.pay').change(function(){
var subtotal = $('.subtotal').val()-0;
var get = $(this).val()-0;
$('.return').val(get - subtotal);
});
// end
});
</script>
<script type="text/javascript">
// for updating the tax while writing the price .
function changeTax(){
var price = document.getElementById("price").value;
var q = document.getElementById("quantity").value;
var np = Number(price);
var tax = (0.15 * np)*q;
<!-- how to diferenciate concatinate anad plus sign-->
document.getElementById("amount").value = q * np;
var amount = document.getElementById("amount").value;
document.getElementById("tax").value = tax;
document.getElementById("subtotal").value = Number(tax) + Number(amount);
}
</script>
<script>
$(function() {
});
</script>

Categories