How to change name of input text, when adding more inputs - javascript

this is the form
<form action="" method="POST">
<input type="button" value="addmore" onClick="addRow('dataTable')" />
<table id="dataTable" class="TFtable" border="1">
<tr>
<td><label>should be auto increment(like (name1, name2, name3 ...))</label>
<input type="text" required="required" name="DONINID[]" value=""></td>
</tr>
</table>
<input class="submit" type="submit" value="Confirm »" />
</form>
this is the script to add more => script.js:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 20){ // limit the user from creating fields more than your limits
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;
}
}else{
alert("Maximum Passenger per ticket is 20.");
}
}
function deleteRow(tableID) {
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) { // limit the user from removing all the fields
alert("Cannot Remove all the Passenger.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
Now the idia is how to change the label name too as we add more input box it's should be auto increment like:
name1, name2, name3, name3 and when we add it should show us.
thanks in advance.

Add a variable that tracks the next # to use and append it to the contents and name every time you add one.
HTML
<form action="" method="POST">
<input type="button" value="addmore" onClick="addRow('dataTable')" />
<table id="dataTable" class="TFtable" border="1">
<tr>
<td>
<label>Name 1:</label>
<input type="text" required="required" name="name1" />
</td>
</tr>
</table>
<input class="submit" type="submit" value="Confirm »" />
JavaScript
var nextName = 2;
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 20) { // limit the user from creating fields more than your limits
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 = '<label>Name ' + nextName + ':</label>' +
'<input type="text" required="required" name="name' + nextName + '" />';
nextName++;
}
} else {
alert("Maximum Passenger per ticket is 20.");
}
}
function deleteRow(tableID) {
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) { // limit the user from removing all the fields
alert("Cannot Remove all the Passenger.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
Demo: http://jsfiddle.net/BenjaminRay/4jnw0t09/

Related

Onchange in dynamic table only updates input textbox in first row

I want to thank you guys for your response and assistance rendered so far, i am greatful but please i wouldn't mind if you don't get tired on me.
Thanks.
Please i need help with my dynamic table, everything seems to be working fine except for my onchange event for each dynamically added row, it only inserts into the first row, but when i select an option from the second added row, the feilds to be updated from the database remains blank.
I used alert to check, and the onchange seems to be working on all rows just that it is only the first row that changes are effected to the required fields. Bellow is my code for your review.
php script at the top of the page that populates select option data from the database
<?php
$query1 = "SELECT * FROM products";
$result1 = mysqli_query($con, $query1);
$options = "";
while($row3 = mysqli_fetch_array($result1))
{
$options = $options."<option value='$row3[1]'>$row3[2]</option>";
}
?>
My Javascript
<SCRIPT language="javascript">
//function that increases the table row
function addRow(dataTable) {
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
if (rowCount < 4) { // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
row.id = 'row_'+rowCount;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.outerHTML = table.rows[1].cells[i].outerHTML;
}
var listitems= row.getElementsByTagName("input")
for (i=0; i<listitems.length; i++) {
listitems[i].setAttribute("oninput", "calculate('"+row.id+"')");
}
} else {
alert("Maximum Row Reached.");
}
}
//function that reduces the table row
function deleteRow(dataTable) {
var table = document.getElementById("dataTable");
var rowCount = table.rows.length;
for (var i = 1; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null !== chkbox && true === chkbox.checked) {
if (rowCount <= 2) { // limit the user from removing all the fields
alert("Cannot Remove all the Rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
//function that handles the summing of each row & all last column
function calculate(elementID) {
var mainRow = document.getElementById(elementID);
var myBox12 = mainRow.querySelectorAll('[id=item')[0].value;
var myBox23 = mainRow.querySelectorAll('[id=descript')[0].value;
var myBox1 = mainRow.querySelectorAll('[id=uprice')[0].value;
var myBox2 = mainRow.querySelectorAll('[id=price')[0].value;
var total = mainRow.querySelectorAll('[id=qty')[0];
var multiplier = Number(myBox2) || 0;
var myResult1 = myBox1 * multiplier;
var mresult = myResult1.toFixed(2);
total.value = mresult;
var confirm = 10;
var colCount;
var table = document.getElementById("dataTable");
let rows = [...table.querySelectorAll('[name*=qty]')];
let total2 = rows.reduce((prev, current)=>{
let to_be_added = Number(current.value) || 0;
return prev + to_be_added;
},0)
console.log(total2);
$("#sumtotal").val(total2.toFixed(2));
return total2;
}
//function that gets the amount due(balance left)
function amountDue() {
var amount = parseFloat($("#sumtotal").val());
var paidd = parseFloat($("#paid").val());
var balance = amount - paidd;
$("#due").val(balance.toFixed(2));
$("#due2").val(balance.toFixed(2));
//return total2;
}
//function that updates #uprice and #descript from the data base onchange of the select box
function get_item(elementID){
$.ajax({
method:"POST",
url:"get_price.php",
data:{item2:$("#item").val()},
success:function(data){
alert(data);
if(data!='0'){
//$('#descript').val(data);
$('#uprice').val(data);
}else{
alert('Description not available');
}
}
});
$.ajax({
method:"POST",
url:"get_item.php",
data:{item:$("#item").val()},
success:function(data){
alert(data);
if(data!='0'){
$('#descript').val(data);
}else{
alert('Description not available');
}
}
});
}
</SCRIPT>
My html code
<table id="dataTable" class="form">
<thead>
<th style="width:20px"></th>
<th>Item</th>
<th>Description</th>
<th>Unit Price</th>
<th>Item Units</th>
<th>Sub Total (#)</th>
</thead>
<tbody>
<tr id='row_0'>
<td><input style="width:20px" type="checkbox" name="chkbox[]" />
</td>
<td>
<select required="required" name="item" onchange="get_item('row_0')" id="item" placeholder="Item">
<option value="0"> select an item</option>
<?php echo $options;?>
</select>
</td>
<td>
<input type="text" required="required" class="small" name="descript" id="descript" placeholder="Description">
</td>
<td>
<input type="text" required="required" name="uprice[]" oninput="calculate('row_0')" id="uprice" placeholder="unit price">
</td>
<td>
<input type="text" required="required" class="small" name="price[]" oninput="calculate('row_0')" id="price" placeholder="units" value="0">
</td>
<td>
<input type="text" required="required" class="small" name="qty[]" id="qty" placeholder="sub total" value="0.00" readonly="readonly" style="background-color: white">
</td>
</tr>
</tbody>
</table>
<span id="mee"></span>
<input type="button" value="Add" onClick="addRow('dataTable')" class="butto" />
<input type="button" value="Remove" onClick="deleteRow('dataTable')" class="butto"/>
Already mentoined here, but still: How to submit form on change of dropdown list? . When user submits form, use php fetch from databse, with isset($_POST['name'])
I was able to fix it with making the some changes in my get_item() javascript function
function get_item(dropDown){
$.ajax({
method:"POST",
url:"get_item.php",
data:{item:dropDown.value},
success:function(data){
alert(data);
if(data!='0'){
$($(dropDown).parents('tr')[0]).find('input#descript').val(data);
//$('#uprice').val(data);
}else{
alert('Description not available');
}
}
});
}
thanks everyone.

Javascript - remove row after add

I have a form with this filed and by ADD button I can add rows. To remove the rows I have put deleteRow function, but this work only if the checkbox is on the left of the form. The checkbox must be on the right form and when press the delteRow, not work
This is the script:
<form name="books">
<button type="button" onClick="addRow('dataTable')"> ADD Book </button>
<button type="button" onClick="deleteRow('dataTable')"> DEL Book </button>
<table id="dataTable" class="form">
<tr>
<td>Date:
<td><input type="text" class="form-control" name="date_book[]">
<td>Pages:
<td><input type="text" class="form-control" name="book_pages[]">
<td>Pages total:
<td><input type="text" class="form-control" name="book_pages_total">
<td width="51"><input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
</table>
</form>
Javascript function:
function addRow(tableID) {
var table = document.querySelector('#' + tableID);
var lastRow = table.rows[table.rows.length - 1];
// Create a new row by cloning the last one
var newRow = lastRow.cloneNode(true);
var inputs = newRow.querySelectorAll('input');
// Clear all but first input
[].forEach.call(inputs, (input, i) => {if (i) input.value = '';});
// Add the row to the table
lastRow.parentNode.appendChild(newRow);
}
function deleteRow(tableID) {
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) { // limit the user from removing all the fields
alert("You do not remove all rows");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
How to remove the rows when the checkbox is on the right form?
I hope to explain my problem.
Thanks
As pointed out elsewhere, in Roljhon's answer, the problem is the line:
var chkbox = row.cells[0].childNodes[0];
To correct this, you can either change the index from row.cells[0] to the correct index (here it would, as noted in that answer, be 6) or you can make it more flexible, and simply select the appropriate <input> element from the specified <tr> (the row) variable, using the appropriate CSS selector and Element.querySelector()]:
// here we look within the <tr> represented by the 'row' variable:
var chkbox = row
// using Element.querySelector():
.querySelector(
// to find the first (if any) <input> element, with
// its 'type' attribute equal to 'checkbox' and its
// 'name' attribute equal to the string 'chk[]'
// (the square brackets are escaped because otherwise
// they're recognised as part of the CSS selector):
'input[type=checkbox][name="chk\[\]"]'
);
function addRow(tableID) {
var table = document.querySelector('#' + tableID);
var lastRow = table.rows[table.rows.length - 1];
// Create a new row by cloning the last one
var newRow = lastRow.cloneNode(true);
var inputs = newRow.querySelectorAll('input');
// Clear all but first input
[].forEach.call(inputs, (input, i) => {
if (i) input.value = '';
});
// Add the row to the table
lastRow.parentNode.appendChild(newRow);
}
function deleteRow(tableID) {
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.querySelector('input[type=checkbox][name="chk\[\]"]');
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 1) { // limit the user from removing all the fields
alert("You do not remove all rows");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
<form name="books">
<button type="button" onClick="addRow('dataTable')">ADD Book</button>
<button type="button" onClick="deleteRow('dataTable')">DEL Book</button>
<table id="dataTable" class="form">
<tr>
<td>Date:
<td>
<input type="text" class="form-control" name="date_book[]">
<td>Pages:
<td>
<input type="text" class="form-control" name="book_pages[]">
<td>Pages total:
<td>
<input type="text" class="form-control" name="book_pages_total">
<td width="51">
<input type="checkbox" required="required" name="chk[]" checked="checked" />
</td>
</table>
</form>
JS Fiddle demo.
References:
CSS:
CSS Attribute Selectors.
JavaScript
Element.querySelector().
Your pointing to a wrong cell cell[0], it points to tthe first cell not the 6th cell where your checkbox is.
Change it to :
var chkbox = row.cells[6].childNodes[0];

Changing SELECT ID With Loop

I currently have a form that can add new entries on click using javascript. However, I would like to change the id of each subsequent "add-on": e.g. The first tbody has an id of "participant1", but the next one will have an id of "participant2", the eighth "participant8", and so forth.
Here is the excerpt from my main file:
<fieldset class="row2">
<legend>List of Participants</legend>
<p>
<input type="button" value="Add Participant" onclick="addRow('dataTable')" />
<input type="button" value="Clear Participants" onclick="deleteRow('dataTable')" />
<p>(All acions apply only to entries with check marked check boxes only.)</p>
</p>
<table id="dataTable" class="form" border="1">
<tbody>
<tr>
<p>
<td>
<input type="checkbox" required="required" name="chk[]" checked="checked" />
</td>
<td>
<div>Participant: </div>
<select name="participant1" id="participant1">
<option>Person A</option>
<option>Person B</option>
<option>Person C</option>
</select>
</td>
</p>
</tr>
</tbody>
</table>
<div class="clear"></div>
</fieldset>
And here is what I am currently attempting with my JS file:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 50) {
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.id="participant"+ rowCount;
var cellBody = table.rows[0].cells[i].innerHTML;
newcell.innerHTML = replaceAll(cellBody, 'participant1', 'participant' + (rowCount + 1));
console.log(rowCount, newcell.innerHTML)
}
}
else {
alert("More than 50 Participants? Are you sure?");
}
}
function replaceAll(str, find, replace) {
var i = str.indexOf(find);
if (i > -1) {
str = str.replace(find, replace);
i = i + replace.length;
var st2 = str.substring(i);
if (st2.indexOf(find) > -1) {
str = str.substring(0, i) + replaceAll(st2, find, replace);
}
}
return str;
}
But this appears to only be taking in one participant?
You are probably getting javascript errors. May need to wrap the functions in some kind of dom-ready event.
The fiddle here works, but only using jquery and its document ready check.
http://jsfiddle.net/brettwgreen/17om5xpm/
I'd also recommend using (a) jquery and (b) knockout.js.
Once you start using knockout or similar JS framework for this kind of thing, you'll never go back.
JS:
$(document).ready(function() {
window.addRow = function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 50){
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
console.log(colCount);
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
//newcell.id="participant"+ rowCount;
var cellBody = table.rows[0].cells[i].innerHTML;
newcell.innerHTML = replaceAll( cellBody, 'participant1' , 'participant' + (rowCount+1) );
console.log(rowCount, newcell.innerHTML)
}
}
else {
alert("More than 50 Participants? Are you sure?");
}
}
window.replaceAll = function replaceAll(str, find, replace) {
var i = str.indexOf(find);
if (i > -1) {
str = str.replace(find, replace);
i = i + replace.length;
var st2 = str.substring(i);
if(st2.indexOf(find) > -1) {
str = str.substring(0,i) + replaceAll(st2, find, replace);
}
}
return str;
}
});

validate dynamic row text field

My script for dynamic row:
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 ="terms_desc";
element2.setAttribute('size', '80');
cell2.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);
}
}
my jsp coding i want to validate each and every new row text field.
<table id="regforms">
<tr><td>
<table id="dataTable" width="350px" border="1">
<tr>
<td><input type="checkbox" name="chk"/></td>
<td> <input type="text" name="terms_desc" size="80" /> </td>
</tr>
</table>
<input type="button" value="Add Row" onclick="addRow('dataTable')" />
<input type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
please any one help for this to validate each and every row created by using this.
addRow and deleteRow use to add and delete dynamic row
my validation code
function val()
{
if (document.forms[0]['terms_desc'].value == 0)
{
alert("Please Enter Terms");
return false;
}
}

Javascript: fetch values from textbox of a dynamic datagrid. (skipping some textboxes)

i have seen similar questions to this but none can assist me.as my code is missing some results and i don't now why.
as seen on the image above the output is 6 results instead of 12
This is the code am using to get the values
//Fetch Sales**********************************************
function fetchsales(){
var Dt = document.getElementById("sDate").value;
var Usr = document.getElementById("UserID").value;
var Stp = document.getElementById("tstamp").value;
var e = document.getElementById("sdepot");
var Dpt = e.options[e.selectedIndex].value;
var sale = new Array();
var Tbl = document.getElementById('tbl_sales'); //html table
var tbody = Tbl.tBodies[0]; // Optional, based on what is rendered
for (var i = 2; i < tbody.rows.length; i++) {
var row = tbody.rows[i];
for (var j = 2; j < row.cells.length; j++) {
var cell = row.cells[j];
// For Every Cell get the textbox value
var unitsold = cell.childNodes[0].value ;
//Get selectbox distributor
var Sdist = row.cells[1].childNodes[0]; //Select box always on second coloumn
var Distributor = Sdist.options[Sdist.selectedIndex].value;
//Get selectbox Product
var Sprod = tbody.rows[1].cells[j].childNodes[0];
var Product = Sprod.options[Sprod.selectedIndex].value;
sale[(j*i)] = new Array ('('+Dt,Dpt,Product,unitsold,Distributor,Usr,Stp+')<br/>');
}
}
//Debug
var fsale = new Array();
fsale = sale.filter(function(n){return n});
document.getElementById("output").innerHTML = fsale;
}
//End Fetch Sales******************************************************
And this is the Whole Document with the Above code included.
<!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>
<style>
</style>
<script type="text/javascript">
//*********************************Start Add Row **********************************************************
function addRowToTable() {
var tbl = document.getElementById('tbl_sales'); //html table
var columnCount = tbl.rows[0].cells.length; //no. of columns in table
var rowCount = tbl.rows.length; //no. of rows in table
var row = tbl.insertRow(rowCount); //insert a row method
// For Every Row Added a Checkbox on first cell--------------------------------------
var cell_1 = row.insertCell(0); //Create a new cell
var element_1 = document.createElement("input"); //create a new element
element_1.type = "checkbox"; //set element type
element_1.setAttribute('id', 'newCheckbox'); //set id attribute
cell_1.appendChild(element_1); //Append element to created cell
// For Every Row Added add a Select box on Second cell------------------------------
var cell_2 = row.insertCell(1);
var element_2 = document.createElement('select');
element_2.name = 'SelDist' + rowCount;
element_2.className = 'styled-select';
element_2.options[0] = new Option('John Doe', '1');
element_2.options[1] = new Option('Dane Doe', '2');
cell_2.appendChild(element_2);
// For Every Row Added add a textbox on the rest of the cells starting with the 3rd,4th,5th... coloumns going on...
if (columnCount >= 2) { //Add cells for more than 2 columns
for (var i = 3; i <= columnCount; i++) {
var newCel = row.insertCell(i - 1); //create a new cell
var element_3 = document.createElement("input");
element_3.type = "text";
element_3.className = "rounded";
element_3.name = 'txt_r'+ rowCount +'c'+(i-1);
element_3.id = 'txt_r'+ rowCount +'c'+(i-1);
element_3.size = 5;
element_3.value = 'txt_r'+rowCount+'c'+(i-1);
newCel.appendChild(element_3);
}
}
}
//***************************** End Add Row ***************************************************************
// *****************************Start Add Column**********************************************************
function addColumn() {
var tblBodyObj = document.getElementById('tbl_sales').tBodies[0];
var rowCount = tblBodyObj.rows.length;
//for every Coloumn Added Add checkbox on first row ----------------------------------------------
var newchkbxcell = tblBodyObj.rows[0].insertCell(-1);
var element_4 = document.createElement("input");
element_4.type = "checkbox";
element_4.setAttribute('id', 'newCheckbox');
newchkbxcell.appendChild(element_4);
//For Every Coloumn Added add Drop down list on second row-------------------------------------
var newselectboxcell = tblBodyObj.rows[1].insertCell(-1);
var element_5 = document.createElement('select');
element_5.name = 'SelProd' + rowCount;
element_5.className = 'styled-select';
element_5.options[0] = new Option('Product11', '11');
element_5.options[1] = new Option('Product12', '12');
element_5.options[2] = new Option('Product13', '13');
element_5.options[3] = new Option('Product14', '14');
element_5.options[4] = new Option('Product15', '15');
element_5.options[5] = new Option('Product16', '16');
newselectboxcell.appendChild(element_5);
// For Every Coloumn Added add a textbox on the rest of the row cells starting with the 3rd,4th,5th......
for (var i = 2; i < tblBodyObj.rows.length; i++) { //Add cells in all rows starting with 3rd row
var newCell = tblBodyObj.rows[i].insertCell(-1); //create new cell
var ClmCount = ((tblBodyObj.rows[0].cells.length)-1);
var element_6 = document.createElement("input");
element_6.type = "text";
element_6.className = "rounded"
element_6.name = 'txt_r'+ i + 'c' + ClmCount;
element_6.id = 'txt_r'+ i + 'c' + ClmCount;
element_6.size = 5;
element_6.value = 'txt_r'+i+'c'+ClmCount;
newCell.appendChild(element_6)
}
}
//*****************************Start Delete Selected Rows **************************************************
function deleteSelectedRows() {
var tb = document.getElementById('tbl_sales');
var NoOfrows = tb.rows.length;
for (var i = 0; i < NoOfrows; i++) {
var row = tb.rows[i];
var chkbox = row.cells[0].childNodes[0]; //get check box object
if (null != chkbox && true == chkbox.checked) { //wheather check box is selected
tb.deleteRow(i); //delete the selected row
NoOfrows--; //decrease rowcount by 1
i--;
}
}
}
//*****************************End Delete Selected Columns **************************************************
//*****************************Start Delete Selected Columns ************************************************
function deleteSelectedColoumns() {
var tb = document.getElementById('tbl_sales'); //html table
var NoOfcolumns = tb.rows[0].cells.length; //no. of columns in table
for (var clm = 3; clm < NoOfcolumns; clm++) {
var rw = tb.rows[0]; //0th row with checkboxes
var chkbox = rw.cells[clm].childNodes[0];
console.log('Current Coloumn:'+clm+',', NoOfcolumns, chkbox); // test with Ctrl+Shift+K or F12
if (null != chkbox && true == chkbox.checked) {
//-----------------------------------------------------
var lastrow = tb.rows;
for (var x = 0; x < lastrow.length; x++) {
tb.rows[x].deleteCell(clm);
}
//-----------------------------------------
NoOfcolumns--;
clm--;
} else {
//alert("not selected");
}
}
}
//*****************************End Delete Selected Columns **************************************************
//Fetch Sales**********************************************
function fetchsales(){
var Dt = document.getElementById("sDate").value;
var Usr = document.getElementById("UserID").value;
var Stp = document.getElementById("tstamp").value;
var e = document.getElementById("sdepot");
var Dpt = e.options[e.selectedIndex].value;
var sale = new Array();
var Tbl = document.getElementById('tbl_sales'); //html table
var tbody = Tbl.tBodies[0]; // Optional, based on what is rendered
for (var i = 2; i < tbody.rows.length; i++) {
var row = tbody.rows[i];
for (var j = 2; j < row.cells.length; j++) {
var cell = row.cells[j];
// For Every Cell get the textbox value
var unitsold = cell.childNodes[0].value ;
//Get selectbox distributor
var Sdist = row.cells[1].childNodes[0]; //Select box always on second coloumn
var Distributor = Sdist.options[Sdist.selectedIndex].value;
//Get selectbox Product
var Sprod = tbody.rows[1].cells[j].childNodes[0];
var Product = Sprod.options[Sprod.selectedIndex].value;
sale[(j*i)] = new Array ('('+Dt,Dpt,Product,unitsold,Distributor,Usr,Stp+')<br/>');
}
}
//Debug
var fsale = new Array();
fsale = sale.filter(function(n){return n});
document.getElementById("output").innerHTML = fsale;
}
//End Fetch Sales******************************************************
//on loading create 3 coloumns and 2 rows
window.onload = function () {addColumn();addColumn();addColumn();addRowToTable();addRowToTable();};
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Distributor Sales</title>
</head>
<body>
<!--A--->
<div class="datagrid shadow" style="float:left; min-width:160px; width:220px">
<table id="top">
<tbody>
<tr>
<td width="100px">
<label for="textfield2">Date</label>
<input id="sDate" name="sDate" type="date" size="10" class="rounded" value="2013-06-04" />
</td>
</tr>
<tr class="alt">
<td width="220px">
<label for="select">Depot</label>
<select name="sdepot" id="sdepot" class="styled-select">
<option value="1">Muranga</option>
<option value="2" selected="selected">Nyahururu</option>
<option value="3">Karatina</option>
</select>
</td>
</tr>
</tbody>
</table>
</div>
<!--C--->
<div class="datagrid shadow" style="float:left; margin-left:20px; width:250px; min-width:250px">
<table>
<tbody>
<tr>
<td>
<label for="textfield4">User ID</label>
<input id="UserID" name="UserID" type="text" class="rounded" value="121" />
</td>
</tr>
<tr class="alt">
<td>
<label for="textfield5">Time Stamp</label>
<input type="date" name="tstamp" id="tstamp" class="rounded" value="2013-06-02" />
</td>
</tr>
</tbody>
</table>
</div>
<div style="clear:both"></div>
</br>
<div class="mainG gradient-style shadow" style="min-width:500px; min-height:120px">
<table id="tbl_sales" border="1" bordercolor="#E1EEF4" background="table-images/blurry.jpg">
<tr>
<td></td>
<td><input type="button" name="button3" id="button3" value="-Row" onclick="deleteSelectedRows()" />
<input type="button" name="button4" id="button4" value="-Coloumn" onclick="deleteSelectedColoumns()" /></td>
</tr>
<tr>
<td></td>
<td><input type="button" name="addrowbutton" id="adrwbutton" value="+Row" onclick="addRowToTable();" />
<input type="button" name="adclmbutton" id="addclmnbutton" value="+Coloumn" onclick="addColumn()" />
</td>
</tr>
</table>
</div>
<div style="clear:both"></div>
<br/>
<div class="datagrid shadow" style="float:left; margin-left:20px; width:200px; min-width:200px; padding-left:10px">
<table id="bottom1" style="min-width:200px">
<tbody>
<tr>
<td>
<div align="center"><input name="myBtn" type="submit" value="Save Information" onClick="javascript:fetchsales();">
</td>
</tr>
</tbody>
</table>
</div>
<div style="clear:both"></div>
<br/>
<div id="output"></div>
</body>
</html>
NB: am hoping to concatenate the result to a mysql insert statement
Any assistance will be greatly appreciated.
The problem comes from this line:
sale[(j*i)] = new Array ('('+Dt,Dpt,Product,unitsold,Distributor,Usr,Stp+')<br/>');
using the for loops indexes multiplied by themselves doesnt ensure unique array indexes, in some cases they are repeated (like for example 2*3 and 3*2) and the previous value in the array gets overwritten.

Categories

Resources