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;
}
Related
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
}
I have a table where I can dynamically add rows. I want to get the data in each row to a php array when I submit the save button . Can please somebody help me on this. I'm new to java-script and know very little about it. Thank you!
<HTML>
<HEAD>
<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
<SCRIPT language="javascript">
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);
cell2.innerHTML = rowCount + 1;
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell3.appendChild(element2);
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT type="button" value="Add Row" onClick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onClick="deleteRow('dataTable')" />
<form action="" method="post">
<?php $i= 1; ?>
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD><INPUT type="checkbox" name="chk"/></TD>
<TD> 1 </TD>
<TD> <INPUT type="text" name="harsh"/> </TD>
</TR>
</TABLE>
<input name="saveNewSales" type="submit" value="Save" id="button2" style="text-align:center"/>
</form>
<?php
foreach($_POST as $name => $content) { // Most people refer to $key => $value
echo "The HTML name: $name <br>";
echo "The content of it: $content <br>";
}
?>
</BODY>
</HTML>
Your code is right, just little change over there
<TR>
<TD><INPUT type="checkbox" name="chk"/></TD>
<TD> 1 </TD>
<TD> <INPUT type="text" name="<?php echo $i; ?>"/> </TD>
</TR>
replace with this code
<TR>
<TD><INPUT type="checkbox" name="chkbox[]"/></TD>
<TD> 1 </TD>
<TD> <INPUT type="text" name="txtbox[]"/> </TD>
</TR>
and your work finish
var rows=getElementsByTagName("tr");
var noOfRows=rows.length;
for(int i=0;i<noOfRows;i++){
var html=rows[i].innerhtml; /*a single row's inner html say (<td>apple</td><td>25</td>)*/
var td=html.match(/(?!<td>)([\s*\w*]*)[^<\/td>]/g);
/**
td[0] is 'apple', td[1] is '25'
**/
}
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
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
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();