Changing SELECT ID With Loop - javascript

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;
}
});

Related

Javascript Delete row with checkbox

Hi i'm a beginner and I'm trying to do a simple CRUD Car apps but i cannot delete row with my function deleteRow().
I've create a function call deleteRow i add a checkbox in every row with the createElement method and i'm setting the Id attribute using the setAttribute() method.In my function i'm trying to get to the checkbox to see if its checked and if so using the deleteRow method to delete the row.
function addRow() {
/* check if its empty */
var brandValue = document.getElementById("brand").value;
var modelValue = document.getElementById("model").value;
if (brandValue == "" || modelValue == "") {
return alert("Make sure you enter a brand and a model!")
}
/* Add a row */
"use strict";
var table = document.getElementById("table");
var row = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var td3 = document.createElement("INPUT");
td3.setAttribute("type", "checkbox");
td3.setAttribute("id", "cb");
td1.innerHTML = document.getElementById("brand").value;
td2.innerHTML = document.getElementById("model").value;
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
table.children[0].appendChild(row);
document.getElementById('brand').value = "";
document.getElementById('model').value = "";
}
var temp = 1;
function deleteRow() {
for (var j = temp - 2; j >= 0; j--) {
if (document.table.cb[j].checked) {
document.getElementById("table").deleteRow(j + 1);
}
}
}
<input type="text" id="brand" placeholder="Add a brand">
<input type="text" id="model" placeholder="Add a Model">
<button type="button" onClick="addRow()" id="add">Update</button>
<button type="button" onClick="deleteRow()" id="delete">Delete</button>
<table id="table">
<div class="tableDiv">
<tr>
<th>Brands</th>
<th>Models</th>
<th>Select</th>
</tr>
</div>
</table>
Right now nothing happen when i'm trying to delete and i have nothing in the browser console.
Thanks for your help.
Try this:
const $brand = document.getElementById("brand")
const $model = document.getElementById("model")
const $table = document.getElementById("table")
function addRow() {
/* check if its empty */
if ($brand.value == "" || $model.value == "") {
return alert("Make sure you enter a brand and a model!")
}
let $row = document.createElement("tr");
let $td1 = document.createElement("td");
let $td2 = document.createElement("td");
let $td3 = document.createElement("input");
$td3.setAttribute("type", "checkbox");
$td1.innerHTML = $brand.value;
$td2.innerHTML = $model.value;
$row.appendChild($td1);
$row.appendChild($td2);
$row.appendChild($td3);
$table.children[0].appendChild($row);
$brand.value = "";
$model.value = "";
}
function deleteRow() {
let checkboxs = $table.querySelectorAll("input[type='checkbox']:checked")
checkboxs.forEach(checkbox => checkbox.parentElement.remove())
}
<input type="text" id="brand" placeholder="Add a brand"></input>
<input type="text" id="model" placeholder="Add a Model"></input>
<button type="button" onClick="addRow()" id="add">Update</button>
<button type="button" onClick="deleteRow()" id="delete">Delete</button>
</div>
<table id="table">
<div class="tableDiv" <tr>
<th>Brands</th>
<th>Models</th>
<th>Select</th>
</tr>
</div>
</table>
for (var j = temp - 2; j >= 0; j--) { this loop never starts due to temp being 1.
1 - 2 = -1 so the loop condition (j >= 0) is never true.
Your main mistake is that you don't need to iterate anything, you can select the checked elements directly.
Try using document.querySelector("#table input[type='checkbox']:checked")
Another thing is that now you are assigning the same id to multiple elements. This should not be done, it can lead to unexpected behavior. Consider using class or custom attribute instead
let checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
checkboxes.forEach(checkbox => checkbox.parentElement.parentElement.remove());

use input type to print out the date in year-mm-dd

I have three inputs for the user with date, activity and time. In the date field when the page starts i want the day of the date printet out in the label like this for example: 2015-12-20 and the user can change it if she/he wants.. But i try to make something with a function but cant get it work.
Below is my code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<link href="6.1.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<form>
Date: <input type="text" id="Datum" name="Date" value=DateTime()>
Activity: <input type="text" id="Activity" name="Activ">
Time: <input type="text" id="time" name="Time">
<input type="button" onclick="AddRow()" value="Lägg till data!">
</form>
<table id="myTable">
<tr>
<td>Datum</td>
<td>Aktivit</td>
<td>Tid</td>
<td>Klar?</td>
</tr>
</table>
<button id="buttonforsend" onclick="SendData()">Skicka grönmarkerad data! </button>
<script>
function DateTime() {
var s = document.getElementById("Datum");
s = "";
var myYear = new Date();
s += myYear.getFullYear() + "-";
s += (myYear.getMonth() + 1) + "-";
s += myYear.getDate();
return s;
}
function AddRow()
{
var $check = document.createElement("INPUT");
$check.setAttribute("type", "checkbox");
$check.setAttribute("checked", "true");
$check.setAttribute("class", "checks");
$check.addEventListener("click", toggleClass);
function toggleClass() {
if (this.checked == true) {
this.parentNode.parentNode.className = "Green";
} else {
this.parentNode.parentNode.className = "Red";
}
}
var date = document.getElementById("Datum");
var activity = document.getElementById("Activity");
var time = document.getElementById("time");
var table = document.getElementById("myTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = date.value;
row.insertCell(1).innerHTML = activity.value;
row.insertCell(2).innerHTML = time.value;
row.insertCell(3).appendChild($check).value;
}
function addTable() {
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('TABLE');
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < 3; i++) {
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (var j = 0; j < 4; j++) {
var td = document.createElement('TD');
td.appendChild(document.createTextNode("Cell " + i + "," + j));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
}
function CheckData() {
var $arr = [];
var tb = document.getElementById("myTable");
var checks = tb.querySelectorAll(".checks"),
chk, tr;
for (var i = 0; i < checks.length; i++) {
chk = checks[i];
if (chk.checked) {
tr = chk.closest ? chk.closest('tr') : chk.parentNode.parentNode;
$arr.push({
date: tr.cells[0].innerText,
activity: tr.cells[1].innerText,
time: tr.cells[2].innerText
});
}
}
return $arr;
}
function SendData()
{
var obj = {Data: CheckData()};
var jsonString = "jsonString=" + (JSON.stringify(obj));
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","JSON_H.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form- urlencoded");
xmlhttp.setRequestHeader("Content-Length", jsonString.length);
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState === 4 && (xmlhttp.status === 200)){
alert(xmlhttp.responseText);
}
};
xmlhttp.send(jsonString);
}
</script>
</body>
</html>
You need to call DateTime and insert it's value in the input field, setting value=DateTime() won't set the value. For ex:
document.getElementById("Datum").value=DateTime();
Complete Code:
function DateTime() {
var s = document.getElementById("Datum");
s = "";
var myYear = new Date();
s += myYear.getFullYear() + "-";
s += (myYear.getMonth() + 1) + "-";
s += myYear.getDate();
return s;
}
document.getElementById("Datum").value=DateTime(); // This will insert the value
<form>
Date: <input type="text" id="Datum" name="Date" value="">
Activity: <input type="text" id="Activity" name="Activ">
Time: <input type="text" id="time" name="Time">
<input type="button" onclick="AddRow()" value="Lägg till data!">
</form>

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

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/

Insert multiple rows and columns to a table in html dynamically using javascript code

I am trying to insert multiple rows and columns to create a table in html dynamically by selecting the number of rows and columns in dropdown list using javascript code like in MS Word.
For example if I select number of rows as 5 and number of columns as 5 from the dropdown list of numbers. 5 rows and 5 columns should get displayed.
My question is how can I add multiple rows and columns dynamically to create a table by selecting the number of rows and columns from the drop down list.
Since, <table> element is the one of the most complex structures in HTML, HTML DOM provide new interface HTMLTableElement with special properties and methods for manipulating the layout and presentation of tables in an HTML document.
So, if you want to accomplish expected result using DOM standards you can use something like this:
Demo old
Demo new
HTML:
<ul>
<li>
<label for="column">Add a Column</label>
<input type="number" id="column" />
</li>
<li>
<label for="row">Add a Row</label>
<input type="number" id="row" />
</li>
<li>
<input type="button" value="Generate" id="btnGen" />
<input type="button" value="Copy to Clipboard" id="copy" />
</li>
</ul>
<div id="wrap"></div>
JS new:
JavaScript was improved.
(function (window, document, undefined) {
"use strict";
var wrap = document.getElementById("wrap"),
setColumn = document.getElementById("column"),
setRow = document.getElementById("row"),
btnGen = document.getElementById("btnGen"),
btnCopy = document.getElementById("btnCopy");
btnGen.addEventListener("click", generateTable);
btnCopy.addEventListener("click", copyTo);
function generateTable(e) {
var newTable = document.createElement("table"),
tBody = newTable.createTBody(),
nOfColumns = parseInt(setColumn.value, 10),
nOfRows = parseInt(setRow.value, 10),
row = generateRow(nOfColumns);
newTable.createCaption().appendChild(document.createTextNode("Generated Table"));
for (var i = 0; i < nOfRows; i++) {
tBody.appendChild(row.cloneNode(true));
}
(wrap.hasChildNodes() ? wrap.replaceChild : wrap.appendChild).call(wrap, newTable, wrap.children[0]);
}
function generateRow(n) {
var row = document.createElement("tr"),
text = document.createTextNode("cell");
for (var i = 0; i < n; i++) {
row.insertCell().appendChild(text.cloneNode(true));
}
return row.cloneNode(true);
}
function copyTo(e) {
prompt("Copy to clipboard: Ctrl+C, Enter", wrap.innerHTML);
}
}(window, window.document));
JS old:
(function () {
"use strict";
var wrap = document.getElementById("wrap"),
setColumn = document.getElementById("column"),
setRow = document.getElementById("row"),
btnGen = document.getElementById("btnGen"),
copy = document.getElementById("copy"),
nOfColumns = -1,
nOfRows = -1;
btnGen.addEventListener("click", generateTable);
copy.addEventListener("click", copyTo);
function generateTable(e) {
var newTable = document.createElement("table"),
caption = newTable.createCaption(),
//tHead = newTable.createTHead(),
//tFoot = newTable.createTFoot(),
tBody = newTable.createTBody();
nOfColumns = parseInt(setColumn.value, 10);
nOfRows = parseInt(setRow.value, 10);
caption.appendChild(document.createTextNode("Generated Table"));
// appendRows(tHead, 1);
// appendRows(tFoot, 1);
appendRows(tBody);
(wrap.hasChildNodes() ? wrap.replaceChild : wrap.appendChild).call(wrap, newTable, wrap.firstElementChild);
}
function appendColumns(tElement, count) {
var cell = null,
indexOfRow = [].indexOf.call(tElement.parentNode.rows, tElement) + 1,
indexOfColumn = -1;
count = count || nOfColumns;
for (var i = 0; i < count; i++) {
cell = tElement.insertCell(i);
indexOfColumn = [].indexOf.call(tElement.cells, cell) + 1;
cell.appendChild(document.createTextNode("Cell " + indexOfColumn + "," + indexOfRow));
}
}
function appendRows(tElement, count) {
var row = null;
count = count || nOfRows;
for (var i = 0; i < count; i++) {
row = tElement.insertRow(i);
appendColumns(row);
}
}
function copyTo(e) {
prompt("Copy to clipboard: Ctrl+C, Enter", wrap.innerHTML);
}
}());
If you want to copy generated result to clipboard you can look at answer of Jarek Milewski - How to copy to the clipboard in JavaScript?
You can use this function to generate dynamic table with no of rows and cols you want:
function createTable() {
var a, b, tableEle, rowEle, colEle;
var myTableDiv = document.getElementById("DynamicTable");
a = document.getElementById('txtRows').value; //No of rows you want
b = document.getElementById('txtColumns').value; //No of column you want
if (a == "" || b == "") {
alert("Please enter some numeric value");
} else {
tableEle = document.createElement('table');
for (var i = 0; i < a; i++) {
rowEle = document.createElement('tr');
for (var j = 0; j < b; j++) {
colEle = document.createElement('td');
rowEle.appendChild(colEle);
}
tableEle.appendChild(rowEle);
}
$(myTableDiv).html(tableEle);
}
}
Try something like this:
var
tds = '<td>Data'.repeat(col_cnt),
trs = ('<tr>'+tds).repeat(row_cnt),
table = '<table>' + trs + '</table>;
Then place the table in your container:
document.getElementById('tablePreviewArea').innerHTML = table;
Or with JQuery:
$('#tablePreviewArea').html(table);
Here is the JSFiddle using native js.
Here is the JSFiddle using jQuery.
About the string repeat function
I got the repeat function from here:
String.prototype.repeat = function( num )
{
return new Array( num + 1 ).join( this );
}
I had one sample code...try this and modify it according to your requirement. May it helps you out.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<style type="text/css">
#mytab td{
width:100px;
height:20px;
background:#cccccc;
}
</style>
<script type="text/javascript">
function addRow(){
var root=document.getElementById('mytab').getElementsByTagName('tbody')[0];
var rows=root.getElementsByTagName('tr');
var clone=cloneEl(rows[rows.length-1]);
root.appendChild(clone);
}
function addColumn(){
var rows=document.getElementById('mytab').getElementsByTagName('tr'), i=0, r, c, clone;
while(r=rows[i++]){
c=r.getElementsByTagName('td');
clone=cloneEl(c[c.length-1]);
c[0].parentNode.appendChild(clone);
}
}
function cloneEl(el){
var clo=el.cloneNode(true);
return clo;
}
</script>
</head>
<body>
<form action="">
<input type="button" value="Add a Row" onclick="addRow()">
<input type="button" value="Add a Column" onclick="addColumn()">
</form>
<br>
<table id="mytab" border="1" cellspacing="0" cellpadding="0">
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
Instead of button , you can use select menu and pass the value to variable. It will create row ,column as per the value.

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