insert multiple rows to mysql database [duplicate] - php

This question already has answers here:
Best way to INSERT many values in mysqli?
(4 answers)
Closed 1 year ago.
i am trying to insert multiple rows to mysql but it only sends last row.
i am using javascript to create rows dynamically but it is sending only the last row
this is my form file code
index.php
<style type="text/css">
table,tr,td{border:0px solid black;}
</style>
<table id="titlebar" cellspacing="0px">
<tr>
<td style="width:20px;">✓</td>
<td style="width:160px;">Show</td>
<td style="width:62px;">season</td>
<td style="width:63px;">episode</td>
<td style="width:100px;">language</td>
<td style="width:190px;">Link 1</td>
<td style="width:190px;">Link 2</td>
</tr>
</table>
<form action="send.php" method="POST">
<table id="dataTable" width="auto" style="margin:-4px 0 0 0;" cellspacing="0px">
<tr>
<td style="width:20px;"><INPUT type="checkbox" name="chk" /></td>
<td><INPUT type="text" name="series" style="width:160px;" autocomplete="on" placeholder="Show" required/></td>
<td><INPUT type="text" name="season" style="width:62px;" autocomplete="on" placeholder="season" required/></td>
<td><INPUT type="text" name="episode" style="width:63px;" autocomplete="on" placeholder="episode" required/></td>
<td>
<SELECT name="language" style="width:100px;">
<OPTION value="one">one</OPTION>
<OPTION value="two">two</OPTION>
<OPTION value="three">three</OPTION>
<OPTION value="four">four</OPTION>
<OPTION value="five">five</OPTION>
<OPTION value="six">six</OPTION>
<OPTION value="seven">seven</OPTION>
</SELECT>
</td>
<td><INPUT type="text" name="link_1" style="width:190px;" autocomplete="on" placeholder="link 1" required/></td>
<td><INPUT type="text" name="link_2" style="width:190px;" autocomplete="on" placeholder="link 2" required/></td>
</tr>
</table>
<INPUT type="button" value="Add row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete row" onclick="deleteRow('dataTable')" />
<INPUT type="submit" value="Send"/>
</form>
<script language="Javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "text":
newcell.childNodes[0].value = "";
break;
case "text":
newcell.childNodes[0].value = "";
break;
case "text":
newcell.childNodes[0].value = "";
break;
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
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) {
if(rowCount <= 1) {
alert("Cant delete all rows");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</script>
and this my post code
send.php
<?php
include('mysql.php');
$seriesV = mysql_real_escape_string(stripslashes($_POST['series']));
$seasonV = mysql_real_escape_string(stripslashes($_POST['season']));
$episodeV = mysql_real_escape_string(stripslashes($_POST['episode']));
$languageV = mysql_real_escape_string(stripslashes($_POST['language']));
$link_1V = mysql_real_escape_string(stripslashes($_POST['link_1']));
$link_2V = mysql_real_escape_string(stripslashes($_POST['link_2']));
$sql="INSERT INTO 0_stock_master (stock_id,category_id,tax_type_id,description,long_description,sales_account,cogs_account)
VALUES
('$seriesV','$seasonV','$episodeV','$languageV','$link_1V','$link_2V','".time()."')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
Please help to submit all the rows in mysql database.

first change the names of your dynamically created elements.
next you could walk though the entire post data with:
foreach ($_POST as $key => $value)
{
//... get your row values and execute sql
}

Related

How Sum values in dynamic table columns of qty

How Sum values in dynamic table columns of qty, I can get the total of the price1,
but I don't know to sum the column of qty, this is dynamic table, I can add row
by the add button. Please help, I'm new on php.
<html>
<head>
<div>
<script type="text/javascript">
function tot(elem) {
var d=document.getElementById("total").value;
var total=Number(d);
}
var total = 0;
function getValues() {
var qty1 = 0;
var unit = 0;
var obj = document.getElementsByTagName("input");
for(var i=0; i<obj.length; i++){
if(obj[i].name == "qty1[]"){var qty1 = obj[i].value;}
if(obj[i].name == "unit[]"){var unit = obj[i].value;}
if(obj[i].name == "totala[]"){
if(qty1 > 0 && unit > 0)
{obj[i].value = (qty1*unit).toFixed(2);total+=(obj[i].value*1);}
else{obj[i].value = 0;total+=(obj[i].value*1);}
}
}
document.getElementById("total").value = (total*1).toFixed(2);
total=0;
}
</script>
<script>
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
}
}
}
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)
{
if (rowCount <= 1)
{
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch(e)
{
alert(e);
}
getValues();
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="">
<table width="800" border="0">
<tr>
<td colspan="5" align="center">Products</td>
</tr>
<tr align="center">
<td><INPUT type="button" value="Add Row" onclick="addRow('dataTable')" /></td>
<td>
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" /></td>
<td> </td>
<td> </td>
</tr>
<tr align="center">
<td width="169">qty</td>
<td width="145"> </td>
<td width="368">unit</td>
<td width="151">price1</td>
</tr>
</table>
<div>
<table width="800" border="0" class="box4_Box" id="dataTable">
<tr>
<td width="21" valign="top"><input name="chk[]" type="checkbox"/></td>
<td width="280">
<input type="text" name="qty1[]" id="qty" onkeyup="getValues()"onblur=""/></td>
<td width="337">
<input type="text" name="unit[]" id="unit" onkeyup="getValues()" onblur=""/></td>
<td width="144">
<input type="text" name="totala[]" id="totala" onkeyup="getValues()" /></td>
</tr>
</table>
</div>
<div>
<table width="800" border="0">
<tr>
<td width="305"><input type="text" name="qtytotal" id="qtytotal" value="" /></td>
<td width="337"> </td>
<td width="144"><input type="text" name="total" id="total" value="" /></td>
</tr>
</table>
</div>
</form>
</body>
</html>
function sumQty(tableID) {
var total = 0;
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var colCount = row.cells.length;
for (var j = 0; j < cellCount; j++) {
var node = row.cells[j].childNodes[0];
if (node.name == "qty[]") {
total += parseInt(node.value);
}
}
}
return total;
}

adding dynamically added table row values into database

hi i am working on a form which has a table whic adds rows on a button click
but my problem is when i add a new row the counter value goes to 12 instead of getting 2 can anyone help me out
here is my code
<?php
session_start();
if (!isset($_SESSION["username"])) {
header("Location: unauthorize_access.php");
}
require("includes/dbconnect.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Makhtab</title>
<link rel="stylesheet" type="text/css" href="form2/view.css" media="all">
<script type="text/javascript" src="form2/view.js"></script>
<script type="text/javascript" src="form2/calendar.js"></script>
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
function deleteRow(row)
{
var i=row.parentNode.parentNode.rowIndex;
document.getElementById('POITable').deleteRow(i);
}
function insRow()
{
console.log( 'hi');
var x=document.getElementById('POITable');
var new_row = x.rows[1].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 = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
x.appendChild( new_row );
}
</script>
<script language="javascript" type="text/javascript">
var i=1;
function addRow()
{
var tbl = document.getElementById('zimtable');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var firstCell = row.insertCell(0);
var el = document.createElement('input');
el.type = 'text';
el.name = 'zimname_' + i;
el.id = 'zimname_' + i;
el.size = 40;
el.maxlength = 40;
firstCell.appendChild(el);
var secondCell = row.insertCell(1);
var el2 = document.createElement('input');
el2.type = 'text';
el2.name = 'zimmob_' + i;
el2.id = 'zimmob_' + i;
el2.size = 13;
el2.maxlength = 13;
secondCell.appendChild(el2);
// alert(i);
i++;
makhtab.h.value=i;
alert(i);
}
</script>
<script language="javascript" type="text/javascript">
var i=1;
function addalRow()
{
var tbl = document.getElementById('alimtable');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var firstCell = row.insertCell(0);
var el = document.createElement('input');
el.type = 'text';
el.name = 'alimname_' + i;
el.id = 'alimname_' + i;
el.size = 40;
el.maxlength = 40;
firstCell.appendChild(el);
var secondCell = row.insertCell(1);
var el2 = document.createElement('input');
el2.type = 'text';
el2.name = 'alimmob_' + i;
el2.id = 'alimmob_' + i;
el2.size = 13;
el2.maxlength = 13;
secondCell.appendChild(el2);
var thirdCell = row.insertCell(2);
var element4 = document.createElement("select");
element4.name ='qabil_'+i;
var option1 = document.createElement("option");
option1.value='MUFTI';
option1.innerHTML='MUFTI';
element4.appendChild(option1);
var option2 = document.createElement("option");
option2.value='AALIM';
option2.innerHTML='AALIM';
element4.appendChild(option2);
var option3 = document.createElement("option");
option3.value='QARI';
option3.innerHTML='QARI';
element4.appendChild(option3);
var option4 = document.createElement("option");
option4.value='HAFIZ';
option4.innerHTML='HAFIZ';
element4.appendChild(option3);
thirdCell.appendChild(element4);
// alert(i);
i++;
makhtab.r.value=i;
alert(i);
}
</script>
<!--<style type="text/css" title="currentStyle">
#import "tran/css/layout-styles.css";
#import "tran/css/themes/smoothness/jquery-ui-1.8.4.custom.css";
</style>-->
<script type="text/javascript" src="tran/js/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="tran/js/jquery-ui-1.8.14.custom.min.js"></script>
<script type="text/javascript" src="tran/js/jq-ac-script.js"></script>
<script type="text/javascript">
// function checkForm()
// {
// if(makhtab.code.value == "") {
// alert("Error: Code cannot be Empty!");
// makhtab.code.focus();
// return false;
// }
// if(makhtab.name.value == "") {
// alert("Error: Name cannot be Empty!");
// makhtab.name.focus();
// return false;
//}
//if(makhtab.cmbcount.value == "") {
// alert("Error: Country cannot be Empty!");
//makhtab.cmbcount.focus();
// return false;
// }
//if(makhtab.cmbstate.value == "") {
// alert("Error: State cannot be Empty!");
//makhtab.cmbstate.focus();
// return false;
// }
/* if(makhtab.cmbteh.value == "") {
alert("Error: Tehsil cannot be Empty!");
makhtab.cmbteh.focus();
return false;
}
if(makhtab.cmbcity.value == "") {
alert("Error: City cannot be Empty!");
makhtab.cmbcity.focus();
return false;
}
if(makhtab.tel.value == "") {
alert("Error: Telephone cannot be Empty!");
makhtab.tel.focus();
return false;
}
if(makhtab.mob.value == "") {
alert("Error: Mobile cannot be Empty!");
makhtab.mob.focus();
return false;
}
if(makhtab.stu.value == "") {
alert("Error: Students cannot be Empty!");
makhtab.stu.focus();
return false;
}
}*/
</script>
<SCRIPT type="text/javascript">
<!--
pic1 = new Image(16, 16);
pic1.src = "loader.gif";
$(document).ready(function(){
$("#code").change(function() {
var code = $("#code").val();
if(code.length >= 4)
{
$("#status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "check_ct.php",
data: "code="+ code,
success: function(msg){
$("#status").ajaxComplete(function(event, request, settings){
if(msg == 'OK')
{
$("#code").removeClass('object_error'); // if necessary
$("#code").addClass("object_ok");
$(this).html(' <img src="tick.gif" align="absmiddle">');
}
else
{
$("#code").removeClass('object_ok'); // if necessary
$("#code").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
else
{
$("#status").html('<font color="red">The code should have at least <strong>4</strong> characters.</font>');
$("#code").removeClass('object_ok'); // if necessary
$("#code").addClass("object_error");
}
});
});
//-->
</SCRIPT>
</head>
<body id="main_body" >
<div id="form_container">
<form id="makhtab" class="appnitro" enctype="multipart/form-data" method="post" onsubmit="return checkForm()" action="submit2.php">
<div class="form_description">
<br />
<h2>Makhtab Details</h2>
<!--<p>This is your form description. Click here to edit.</p>-->
</div>
<table border="0px" width="100%">
<tr>
<td><label class="description" for="element_1">Code</label></td><td><input id="element_1" id="code" name="code" class="element text small" type="text" maxlength="6" value=""/></td>
</tr>
<tr>
<td><label class="description" for="element_1">Name</label></td><td><input id="element_1" name="name" class="element text large" type="text" maxlength="40" value=""/> </td>
</tr>
<tr>
<td><label class="description" for="element_1">Address</label></td><td><input id="element_4_1" name="add1" class="element text large" value="" type="text"></td>
</tr>
<tr>
<td></td><td><input id="element_4_1" name="add2" class="element text large" value="" type="text"></td>
</tr>
<tr>
<td></td><td><input id="element_4_1" name="add3" class="element text large" value="" type="text"></td>
</tr>
<tr>
<td><label class="description" for="element_1">City</label></td><td><select name="cmbcity" class="element text medium" style="font-size:18px;"/>
<option value=""></option>
<?php
$result = mysql_query("SELECT code, `name` from city ") or die(mysql_error());
while ($year = mysql_fetch_array($result)) {
echo "<option value='$year[code]'>$year[name]</option>";
}
?>
</select>
</tr>
<tr>
<td><label class="description" for="element_1">State</label></td><td><select name="cmbstate" class="element text medium" style="font-size:18px;"/>
<option value=""></option>
<?php
$result = mysql_query("SELECT code, `name` from state ") or die(mysql_error());
while ($year = mysql_fetch_array($result)) {
echo "<option value='$year[code]'>$year[name]</option>";
}
?>
</select>
</tr>
</tr>
<tr>
<td><label class="description" for="element_1">Country</label></td><td><select name="cmbcount" class="element text medium" style="font-size:18px;"/>
<option value=""></option>
<?php
$result = mysql_query("SELECT code, `name` from country ") or die(mysql_error());
while ($year = mysql_fetch_array($result)) {
echo "<option value='$year[code]'>$year[name]</option>";
}
?>
</select>
<tr>
<td><label class="description" for="element_1">Telephone</label></td><td><input id="element_1" name="tel" class="element text medium" type="text" maxlength="255" value=""/></td>
</tr>
<tr>
<td><label class="description" for="element_1">Mobile</label></td><td><input id="element_1" name="mob" class="element text medium" type="text" maxlength="10" value=""/></td>
</tr>
<tr>
<br />
</tr>
</table>
<tr>
<br /><p style="border-bottom: 1px dotted #ccc;"></p><br />
<div class="form_description">
<h2>Zimmedar Details</h2>
</div>
</tr>
<table border="1px" id="zimtable" border="0px" size="100px" cellspacing="0" cellpadding="2">
<tr>
<td><strong>Zimmedar Name</strong></td>
<td><strong>Mobile</strong> </td>
</tr>
<tr>
<td><input name="zimname_0" type="text" id="zimname_0" size="40" maxlength="20" /></td>
<td><input name="zimmob_0" type="text" id="zimmob_0" size="13" maxlength="20" /></td>
</tr>
</table>
<input type="button" value="Add" onclick="addRow();" /><input name="h" type="hidden" id="h" value="1" />
<tr>
<br /><p style="border-bottom: 1px dotted #ccc;"></p><br />
<div class="form_description">
<h2>Muallim Details</h2>
<!--<p>This is your form description. Click here to edit.</p>-->
</div>
</tr>
<table border="1px" id="alimtable" border="0px" size="100px" cellspacing="0" cellpadding="2">
<tr>
<td><strong>Muallim Name</strong></td>
<td><strong>Mobile</strong> </td>
<td><strong>Qabiliyat</strong> </td>
</tr>
<tr>
<td><input name="alimname_0" type="text" id="alimname_0" size="40" maxlength="20" /></td>
<td><input name="alimmob_0" type="text" id="alimmob_0" size="13" maxlength="20" /></td>
<td><select id="qabil_0" name="qabil_0" class="element text large" style="font-size:14px;"/>
<option value="MUFTI">MUFTI</option>
<option value="AALIM">AALIM</option>
<option value="QARI">QARI</option>
<option value="HAFIZ">HAFIZ</option>
</select></td>
</tr>
<input name="r" type="hidden" id="r" value="1" />
</table>
<input type="button" value="Add" onclick="addalRow();" />
<br /><p style="border-bottom: 1px dotted #ccc;"></p><br />
<table border="0px" width="85%">
<tbody><tr>
<td width="105"><label class="description">No. of Students</label></td>
<td width="65"><input type="text" name=stu" size="5" maxlength="5"></input></td>
<td width="105"><label class="description">No. of Batches</label></td><td width="14"><input type="text" name="batch" size="5" maxlength="3"></input></td>
</tr>
<tr>
<input type="submit" name="submit" value="Save"></input>
</tr>
</tbody>
</table>
</div>
</div>
</form>
</body>
</html>
It seems that your problem is that you don't cast your strings as int. + can mean either concatenation or addition, depending on the types of the 2 variables it's used on.
For example:
var x = '1';
var y = 2;
alert(x+y); // 12, since x is a string and y is automatically cast to string.
alert(parseInt(x)+parseInt(y)) = 3; // since we cast both x and y to int.
PS: If you really need help, and for anyone here to read your code, copy the important bits, not the whole file.
PS2: You should start using jQuery - it can save you a lot of time

How to Insert Multiple row into database

this is my code .. My problem is when I create multiple row, only the first row only make it into the database .. The next row is not .. For your information, add row function works well... I use the concept of MVC
View
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
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) {
if(rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</SCRIPT>
<fieldset>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD><INPUT type="checkbox" name="chk[]"/></TD>
<TD><INPUT type="text" name="amount[]"/></TD>
<TD><INPUT type="text" name="date[]" id="date" /></TD>
<td align="center" valign="top" nowrap><input name="count1" type="text" id="count1" size="8" maxlength="10" value="10"></td>
</TR>
</TABLE>
Controller
$count= $_POST['count1'];
$amount= $_POST['amount'];
$date= $_POST['date'];
for($i=0; $i<=10; $i++){
$this->Model->insertBil($date[$i],$amount[$i]);
}
Model
no questions

How to apply counter on dynamically added rows in javascript

I create 2 PHP pages (test.php, getcompany.php)
in test.php page, I have a row with order details. check working DEMO here :
[DEMO] : http://delta-adv.com/test.php
As you saw in demo in first row when I select product it populate company name from database but when I click add row button then in 2nd row when I select product it change company name in top row only. below is the code for test.php
<html>
<head>
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getcompany(productId) {
var strURL="getcompany.php?product="+productId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('companydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
<script type="text/javascript">
function tot(elem) {
var d=document.getElementById("total").value;
var total=Number(d);
var e=document.getElementById("vat5").value;
var vat5=Number(e);
var f=document.getElementById("vat12_5").value;
var vat12_5=Number(f);
var g=document.getElementById("cash_discount").value;
var cash_discount=Number(g);
var h=(total+vat5+vat12_5)-cash_discount;
document.getElementById("grand_total").value = h;
}
var total = 0;
function getValues() {
var qty = 0;
var rate = 0;
var obj = document.getElementsByTagName("input");
for(var i=0; i<obj.length; i++){
if(obj[i].name == "qty[]"){var qty = obj[i].value;}
if(obj[i].name == "rate[]"){var rate = obj[i].value;}
if(obj[i].name == "amt[]"){
if(qty > 0 && rate > 0){obj[i].value = qty*rate;total+=(obj[i].value*1);}
else{obj[i].value = 0;total+=(obj[i].value*1);}
}
}
document.getElementById("total").value = total*1;
total=0;
}
</script>
<script type="text/javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
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)
{
if (rowCount <= 1)
{
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch(e)
{
alert(e);
}
getValues();
}
</script>
</head>
<body>
<form name="gr" method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" onSubmit="return validateForm(this)">
<tr>
<td class="forhead" style="white-space:nowrap;"> </td>
<table width="70%" align="center" cellpadding="0" cellspacing="0" class="normal-text" border="0">
<tr>
<td width="32"></td>
<td width="126">Product</td>
<td width="149">company</td>
<td width="91" class="forhead" style="white-space:nowrap;">Qty</td>
<td width="100" class="forhead" style="white-space:nowrap;">Unit Price</td>
<td width="87" class="forhead" style="white-space:nowrap;">Total</td>
<td width="28" class="forhead" style="white-space:nowrap;"> </td>
<td width="156" class="forhead" style="white-space:nowrap;"><span class="forhead" style="white-space:nowrap;">
<span class="forhead" style="white-space:nowrap;">
<input type="button" value="Add Row" onClick="addRow('dataTable')" >
</span>
<input type="button" value="Delete Row" onClick="deleteRow('dataTable')" >
</span></td>
</tr>
</table>
<table border="0" id="dataTable" width="70%" align="center" cellpadding="0" cellspacing="0" class="normal-text">
<tr>
<td width="31" class="forhead" style="white-space:nowrap;"><input type="checkbox" name="chk[]"/> </td>
<td class="forhead" style="white-space:nowrap;" width="127">
<select name="product" onChange="getcompany(this.value)">
<option value="">Select Product</option>
<option value="1">iphone</option>
<option value="2">ipad</option>
<option value="3">Galaxy S2</option>
</select>
</td>
<td class="forhead" style="white-space:nowrap;" width="148">
<div id="companydiv"><input name="company" value="" /></div>
</td>
<td class="forhead" style="white-space:nowrap;" width="99"><input type="text" name="qty[]" onkeyup="getValues()" style="width:80px;" onBlur=""></td>
<td class="forhead" style="white-space:nowrap;" width="100"><input type="text" name="rate[]" onKeyUp="getValues()" style="width:80px;" value=""></td>
<td class="forhead" style="white-space:nowrap;" width="148"> <input type="text" name="amt[]" style="width:80px;"
onKeyUp="getValues()"></td>
<td width="8" align="right" class="forhead" style="white-space:nowrap;"> </td>
<td class="forhead" style="white-space:nowrap;" width="108"> </td>
</tr>
</table>
<table width="70%" align="center" cellpadding="0" cellspacing="0" class="normal-text" border="0">
<tr>
<td width="169" class="forhead" style="white-space:nowrap;"> </td>
<td width="600" class="forhead" style="white-space:nowrap;"> </td>
</tr>
<tr>
<td align="right"><span class="forhead" style="white-space:nowrap;">Gross Total:</span></td>
<td align="left"><span class="forhead" style="white-space:nowrap;">
<input type="text" id="total" name="total[]" style="width:80px;" value="">
</span></td>
</tr>
<tr>
<td align="center" colspan="2"><input name="Submit" type="submit" value="Save" style="text-decoration:none"/>
<input type="reset" value="Cancel" onClick="window.location.href='<?php echo $_SERVER['PHP_SELF'];?>'"></td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</form>
</body>
</html>
code for getcompany.php
<?php
$product=intval($_GET['product']);
$link = mysql_connect('localhost', 'root', ''); //Localhost configuration
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('test');
$query="SELECT * FROM tbl_company WHERE prod_ID='$product'";
$result=mysql_query($query);
$row=mysql_fetch_array($result);
?>
<input name="company" value="<?php echo $row['company_name']; ?>" />
You don't need to add special ids.
1.) First change the id to a class:
From: <div id="companydiv"><input name="company" value="" /></div>
To: <div class="companydiv"><input name="company" value="" /></div>
2.) Change the select onchange parameter to this:
From: <select name="product" onChange="getcompany(this.value)">
To: <select name="product" onChange="getcompany(this)">
3.) Replace your getcompany function with:
function getcompany(element) { // the parametername has changed
var strURL="getcompany.php?product="+element.value; // this line has changed
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
// last changes here:
element.parentNode.parentNode.getElementsByClassName('companydiv')[0].innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
I see from your page that you use the same ids companyDiv for all new rows. This will be an issue.
See this line in your getCompany success method
document.getElementById('companydiv').innerHTML=req.responseText
Edit
When you add new rows, try giving an id based on the index number of this row. That way, in your <select name="product" onChange="getcompany(this.value)"> onchange method, you can exactly get the div that you are searching for
Edit 2
In your addRow method, check this line var row = table.insertRow(rowCount);
Now to change the id of this row, all you have to do is, (provided your first row has an id '1')
row.id = 'aNewId' + (parseInt(row.nextSibling.id) + 1);
ar=array("product1"=>"company1", "product2"=>"company2");
var str="";
$("#productSelectorId").change(function () {
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("#companySelectorId").text(ar[str]);
}).change();

How to sum the input field values and display it into html Table using Javascript?

I am new to Javascript, Please help to me solve this issue Javascript experts.
I have a registration form that have these above fields. In this form, When I click "Add new registration line", it will insert new insert field like as above. From these, I want to add these hightlighted input fields values and display it in html table. When I check the checkbox, the values should be displayed in invoicable field, Likewise when I uncheck the checkbox, the values should be displayed in Non-Voicable field. I mean the sum of checked values should be displayed in Invoicable field and the sum of unchecked values should be displayed in Non-invoicable field.
This is the code part of the issue i am trying:
<script type="text/javascript">
$(function() {
var i = 8 + 1;
$('input#add').click(function() {
//store in hidden value for total row
document.getElementById("consinvoice").value=i;
$("<span style='margin-left:126px;'>: <select name='RegistrationType_"+i+"' id='RegistrationType_"+i+"' onchange=\"register('Invoicable_"+i+"',this.value,ConsultancyHours_"+i+".value)\"><option value='CH'>Consultancy Hours</option><option value='LH'>Lunch Hours</option><option value='TH'>Transportation Hours</option><option value='OH'>Other Hours</option></select> <input name='ConsultancyHours_"+i+"' type='text' id='ConsultancyHours_"+i+"' size='5' onkeyup=\"invotable(this.id,this.value);\" /><label for='Hourprice'> Std. Hourprice</label> <input name='Hourprice_"+i+"' type='text' id='Hourprice_"+i+"' size='5' /> <label for='Hourprice'>- Discount Hourprice</label> <input name='Hourprice2_"+i+"' type='text' id='Hourprice2_"+i+"' size='5' /><br /><span style='margin-left:652px;'><input name='Invoicable_"+i+"' type='checkbox' id='Invoicable_"+i+"' checked='checked' onclick=\"register('Invoicable_"+i+"',RegistrationType_"+i+".value,ConsultancyHours_"+i+".value)\" /><label for='Invoicable'> Invoicable</label></span><br /></span>").appendTo('dd');
i++;
});
});
</script>
<script type="text/javascript">
//register('Invoicable_"+i+"',RegistrationType_"+i+".value,this.value);
function invotable(getid,getvalue){
var getinvoicetbl = 'invoice_cons';
var previnvoice = document.getElementById(getinvoicetbl).innerHTML;
var dgetid = getid.split("_");
var getcount = document.getElementById("consinvoice").value;
//alert(getcount);
totalterm =0;
for (j=8;j<=getcount;j++)
{
totalterm += parseInt(document.getElementById("ConsultancyHours_"+j).value);
//register('Invoicable_'+j,document.getElementById("RegistrationType_"+j).value,document.getElementById("ConsultancyHours_"+j).value);
}
document.getElementById(getinvoicetbl).innerHTML = totalterm;
}
function register(getvoice,gettype,getvalue){
//alert(getvoice);
var checkbox = document.getElementById(getvoice).checked;
var getinvoice = 'invoice_cons';
var getnovoice = 'ninvoice_cons';
switch (gettype)
{
case "CH":
if(checkbox ==true){
//alert("true");
document.getElementById(getinvoice).innerHTML = parseInt(document.getElementById("invoice_cons").innerHTML)+parseInt(getvalue);
document.getElementById("totinvoice").value = document.getElementById(getinvoice).innerHTML;
document.getElementById(getnovoice).innerHTML = document.getElementById("totinvoice").value - getvalue;
alert(document.getElementById("totinvoice").value);
alert(document.getElementById(getnovoice).innerHTML);
} else {
alert(document.getElementById("totinvoice").value);
document.getElementById(getnovoice).innerHTML = parseInt(getvalue);
document.getElementById("totinvoice").value = document.getElementById(getnovoice).innerHTML;
document.getElementById(getinvoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue;
}
break;
case "LH":
if(checkbox ==true ){
//alert("true");
document.getElementById(getinvoice).innerHTML = parseInt(document.getElementById("invoice_cons").innerHTML)+parseInt(getvalue);
document.getElementById("totinvoice").value = document.getElementById(getinvoice).innerHTML;
document.getElementById(getnovoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue;
} else {
document.getElementById(getnovoice).innerHTML = parseInt(document.getElementById("invoice_cons").value)+parseInt(getvalue);
document.getElementById("totinvoice").value = document.getElementById(getnovoice).innerHTML;
document.getElementById(getinvoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue;
}
default:
if(checkbox ==true){
//alert("true");
document.getElementById(getinvoice).innerHTML = parseInt(document.getElementById("invoice_cons").innerHTML)+parseInt(getvalue);
document.getElementById("totinvoice").value = document.getElementById(getinvoice).innerHTML;
document.getElementById(getnovoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue;
} else {
document.getElementById(getnovoice).innerHTML = parseInt(document.getElementById("invoice_cons").value)+parseInt(getvalue);
document.getElementById("totinvoice").value = document.getElementById(getnovoice).innerHTML;
document.getElementById(getinvoice).innerHTML = document.getElementById("invoice_cons").innerHTML - getvalue;
}
}
}
</script>
<input type="hidden" name="consinvoice" id="consinvoice" value="8" />
<input type="hidden" name="totinvoice" id="totinvoice" value="0" />
<input type="hidden" name="fromtinvoice" id="fromtinvoice" value="0" />
<td width="220">
<span id="insert_table">
<table class="" id="invtable" width="150" border="1">
<tr>
<td align="right">
</td>
<td align="right" style="padding-left:15px; padding-bottom:10px;">
Invoicable
</td>
<td align="right" style="padding-left:15px; padding-bottom:10px;">
Non-Invoicable
</td>
<td align="right" style="padding-left:15px; padding-bottom:10px;">
Total
</td>
</tr>
<tr>
<td style="padding-bottom:10px;">Consultancy</td>
<td align="right" id="invoice_cons">-</td>
<td align="right" id="ninvoice_cons">-</td>
<td align="right" >-</td>
</tr>
<tr>
<td style="padding-bottom:10px;">Transportation</td>
<td align="right" id="invoice_trans">-</td>
<td align="right" id="ninvoice_trans">-</td>
<td align="right" >-</td>
</tr>
<tr>
<td style="padding-bottom:10px;">Lunch</td>
<td align="right" id="invoice_lun">-</td>
<td align="right" id="ninvoice_lun">-</td>
<td align="right" >-</td>
</tr>
<tr>
<td style="padding-bottom:10px;">Total</td>
<td align="right" id="invoice_tot">-</td>
<td align="right" id="ninvoice_tot">-</td>
<td align="right" >-</td>
</tr>
<tr>
</table>
</span>
</table>
<p>
<label for="RegistrationType">
Type
</label>
<span style="margin-left:92px;">
: <select name="RegistrationType_8" id="RegistrationType_8" onchange="register('Invoicable_8',this.value,ConsultancyHours_8.value)">
<option value="CH">Consultancy Hours</option>
<option value="LH">Lunch Hours</option>
<option value="TH">Transportation Hours</option>
<option value="OH">Other Hours</option>
</select>
<input name="ConsultancyHours_8" type="text" id="ConsultancyHours_8" size="5" onkeyup="invotable(this.id,this.value); " />
<label for="Hourprice">
Std. Hourprice
</label>
<input name="Hourprice_8" type="text" id="Hourprice_8" size="5" />
<label for="Hourprice">
- Discount Hourprice
</label>
<input name="Hourprice2_8" type="text" id="Hourprice2_8" size="5" />
<input name="Invoicable_8" type="checkbox" id="Invoicable_8" onclick="register('Invoicable_8',RegistrationType_8.value,ConsultancyHours_8.value)" checked="checked" />
<label for="Invoicable">
Invoicable
</label>
<dd id="insert_row">
</dd>
</span>
</p>
<p>
<span style="margin-left:132px;">
<input type="button" id="add" value="Add new registration line" />
</span>
</p>
<div style="margin-left:324px;">
</div>
<br />
<p>
<span style="margin-left:132px;">
<input type="submit" name="Submit" id="Submit" value="Save registration" />
</span>
</p>
You can create a function to add new row dynamically and other function to calculate the hour by scaning the form, then when the window is loaded, call the add row function to start. There is the source code that I created:
<!DOCTYPE html>
<style>
body{margin:0}
body,th,td{font:16px Arial, Helvetica, sans-serif}
table{border-spacing:0;border-collapse:collapse;table-layout:fixed}
th,td{white-space:nowrap;overflow:hidden}
th{font-weight:700}
#invtable{width:500px;margin:10px auto;border:1px solid #000}
#invtable th, #invtable td{border:1px solid #000}
#registrationForm{width:100%}
#registrationForm td{text-align:center}
#registrationForm input[type="number"]{width:140px}
</style>
<table id="invtable" width="150">
<tr>
<th>Type</th>
<th>Invoicable</th>
<th>Non-Invoicable</th>
<th>Total</th>
</tr>
<tr id="consultancy">
<th>Consultancy</th>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr id="transportation">
<th>Transportation</th>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr id="lunch">
<th>Lunch</th>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr id="other">
<th>Other</th>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr id="total">
<th>Total</th>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
</table>
<table id="registrationForm"></table>
<p><input type="button" id="addNewRegistrationLine" value="Add new registration line"></p>
<p><input type="submit" id="saveRegistration" value="Save registration"></p>
<script>
var doc = document;
function calculateHour() {
var registrationForm = doc.getElementById('registrationForm');
var registrationFormRows = registrationForm.rows
var typeValue = {'CH' : [0,0], 'LH' : [0,0], 'TH' : [0,0], 'OH' : [0,0]};
for (var i = 0, registrationFormRowsLength = registrationFormRows.length, typeSelect, inputs, hourInput, isInvoicable; i < registrationFormRowsLength; ++i) {
typeSelect = registrationFormRows[i].getElementsByTagName('SELECT')[0];
inputs = registrationFormRows[i].getElementsByTagName('INPUT');
hourInput = inputs[0];
isInvoicable = inputs[inputs.length - 1].checked ? 0 : 1;
typeValue[typeSelect.value][isInvoicable] += hourInput.value - 0;
}
var total = [0, 0]
var consultancyCells = doc.getElementById('consultancy').cells;
consultancyCells[1].innerHTML = typeValue['CH'][0];
total[0] += typeValue['CH'][0];
consultancyCells[2].innerHTML = typeValue['CH'][1];
total[1] += typeValue['CH'][1];
consultancyCells[3].innerHTML = typeValue['CH'][0] + typeValue['CH'][1];
var transportationCells = doc.getElementById('transportation').cells;
transportationCells[1].innerHTML = typeValue['TH'][0];
total[0] += typeValue['TH'][0];
transportationCells[2].innerHTML = typeValue['TH'][1];
total[1] += typeValue['TH'][1];
transportationCells[3].innerHTML = typeValue['TH'][0] + typeValue['TH'][1];
var lunchCells = doc.getElementById('lunch').cells;
lunchCells[1].innerHTML = typeValue['LH'][0];
total[0] += typeValue['LH'][0];
lunchCells[2].innerHTML = typeValue['LH'][1];
total[1] += typeValue['LH'][1];
lunchCells[3].innerHTML = typeValue['LH'][0] + typeValue['LH'][1];
var otherCells = doc.getElementById('other').cells;
otherCells[1].innerHTML = typeValue['OH'][0];
total[0] += typeValue['OH'][0];
otherCells[2].innerHTML = typeValue['OH'][1];
total[1] += typeValue['OH'][1];
otherCells[3].innerHTML = typeValue['OH'][0] + typeValue['OH'][1];
var totalCells = doc.getElementById('total').cells;
totalCells[1].innerHTML = total[0];
totalCells[2].innerHTML = total[1];
totalCells[3].innerHTML = total[0] + total[1];
}
function addNewRegistrationLine() {
var registrationForm = doc.getElementById('registrationForm');
var row = registrationForm.insertRow(registrationForm.rows.length);
var typeSelectCell = row.insertCell(0);
var type = [['CH', 'Consultancy Hours'], ['LH', 'Lunch Hours'], ['TH', 'Transportation Hours'], ['OH', 'Other Hours']];
var typeSelect = doc.createElement('SELECT');
for (var i = 0, typeLength = type.length, option; i < typeLength; ++i) {
option = doc.createElement('OPTION');
option.value = type[i][0];
option.innerHTML = type[i][1];
typeSelect.appendChild(option);
}
typeSelect.onchange = calculateHour;
var typeLabel = doc.createElement('LABEL');
typeLabel.innerHTML = 'Type';
typeLabel.appendChild(typeSelect);
typeSelectCell.appendChild(typeLabel);
var hourInput = doc.createElement('INPUT');
hourInput.type = 'number';
hourInput.onkeyup = calculateHour;
typeSelectCell.appendChild(hourInput);
var hourPriceInputCell = row.insertCell(1);
var hourPriceInput = doc.createElement('INPUT');
hourPriceInput.type = 'number';
var hourPriceLabel = doc.createElement('LABEL');
hourPriceLabel.innerHTML = 'Std. Hourprice';
hourPriceLabel.appendChild(hourPriceInput);
hourPriceInputCell.appendChild(hourPriceLabel);
var discountInputCell = row.insertCell(2);
var discountInput = doc.createElement('INPUT');
discountInput.type = 'number';
var discountLabel = doc.createElement('LABEL');
discountLabel.innerHTML = '- Discount Hourprice';
discountLabel.appendChild(discountInput);
discountInputCell.appendChild(discountLabel);
var invoicableCheckBoxCell = row.insertCell(3);
var invoicableCheckBox = doc.createElement('INPUT');
invoicableCheckBox.type = 'checkbox';
invoicableCheckBox.onclick = calculateHour;
var invoicableLabel = doc.createElement('LABEL');
invoicableLabel.appendChild(invoicableCheckBox);
invoicableLabel.appendChild(document.createTextNode('Invoicable');
invoicableCheckBoxCell.appendChild(invoicableLabel);
}
doc.getElementById('addNewRegistrationLine').onclick = addNewRegistrationLine;
window.onload = function() {
addNewRegistrationLine();
};
</script>
Live example
since it appears that you are using the Jquery Framework you can use the template feature which will allow you to use your javascript data and create html from it, I personally have not used it though.But since you also tagged this with PHP. Why not just do it in PHP?
For Example:
$formData[];
foreach($_POST AS $field => $value) {
$formData[$field] = $value;
}
Then all your data is in an array and much easier to work with. Just make sure to put in the form tag and use the method=“post” attribute.

Categories