Get values from dynamic table and draws it with google charts - javascript

I'm trying to get the values from the dynamic table and after that I want draw it with Google charts, but the code doesn't work, I can't understand what's the problem. I think the problem is related to the method that I use to get the value from the table, but I'm not sure.
When I get the values and I try to draw it, Google returns the following error:
Data column(s) for axis #0 cannot be of type string
Can anyone help me to fix my code please?
Link to JSFiddle: https://jsfiddle.net/macco_cl/qaogs3sx/
var theTable, theTableBody
var myForm = document.forms.myForm;
var png = document.getElementById("png");
function init() {
theTable = (document.all) ? document.all.myTABLE :
document.getElementById("myTABLE")
theTableBody = theTable.tBodies[0]
}
function appendRow(form) {
insertTableRow(form, -1)
}
function addRow(form) {
insertTableRow(form, form.insertIndex.value)
}
function insertTableRow(form, where) {
var now = new Date()
var nowData = [now.getHours(), now.getMinutes(), now.getSeconds(),
now.getMilliseconds()]
clearBGColors()
var newCell
var newRow = theTableBody.insertRow(where)
for (var i = 0; i < nowData.length; i++) {
newCell = newRow.insertCell(i)
newCell.innerHTML = nowData[i]
newCell.style.backgroundColor = "salmon"
}
updateRowCounters(form)
}
function removeRow(form) {
theTableBody.deleteRow(form.deleteIndex.value)
updateRowCounters(form)
}
function insertTHEAD(form) {
var THEADData = ["Hours","Minutes","Seconds","Milliseconds"]
var newCell
var newTHEAD = theTable.createTHead()
newTHEAD.id = "myTHEAD"
var newRow = newTHEAD.insertRow(-1)
for (var i = 0; i < THEADData.length; i++) {
newCell = newRow.insertCell(i)
newCell.innerHTML = THEADData[i]
}
updateRowCounters(form)
form.addTHEAD.disabled = true
form.deleteTHEAD.disabled = false
}
function removeTHEAD(form) {
theTable.deleteTHead()
updateRowCounters(form)
form.addTHEAD.disabled = false
form.deleteTHEAD.disabled = true
}
function insertTFOOT(form) {
var TFOOTData = ["Hours","Minutes","Seconds","Milliseconds"]
var newCell
var newTFOOT = theTable.createTFoot()
newTFOOT.id = "myTFOOT"
var newRow = newTFOOT.insertRow(-1)
for (var i = 0; i < TFOOTData.length; i++) {
newCell = newRow.insertCell(i)
newCell.innerHTML = TFOOTData[i]
}
updateRowCounters(form)
form.addTFOOT.disabled = true
form.deleteTFOOT.disabled = false
}
function removeTFOOT(form) {
theTable.deleteTFoot()
updateRowCounters(form)
form.addTFOOT.disabled = false
form.deleteTFOOT.disabled = true
}
function insertCaption(form) {
var captionData = form.captionText.value
var newCaption = theTable.createCaption()
newCaption.innerHTML = captionData
form.addCaption.disabled = true
form.deleteCaption.disabled = false
}
function removeCaption(form) {
theTable.deleteCaption()
form.addCaption.disabled = false
form.deleteCaption.disabled = true
}
// housekeeping functions
function updateRowCounters(form) {
var sel1 = form.insertIndex
var sel2 = form.deleteIndex
sel1.options.length = 0
sel2.options.length = 0
for (var i = 0; i < theTableBody.rows.length; i++) {
sel1.options[i] = new Option(i, i)
sel2.options[i] = new Option(i, i)
}
form.removeRowBtn.disabled = (i==0)
}
function clearBGColors() {
for (var i = 0; i < theTableBody.rows.length; i++) {
for (var j = 0; j < theTableBody.rows[i].cells.length; j++) {
theTableBody.rows[i].cells[j].style.backgroundColor = ""
}
}
}
function GetCellValues() {
var table = document.getElementById("myTABLE");
for (var r = 0, n = table.rows.length; r < n; r++) {
for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
alert(table.rows[r].cells[c].innerHTML);
}
}
return table;
}
function mostra() {
document.getElementById("chart_div").style.display="block";
}
function nascondi() {
document.getElementById("chart_div").style.display="none";
}
function finestra(){
if(tf == true){
window.open("pngbar.html");
//document.getElementById("chart_div").style.display="none";
}
}
function setDati(){
//if(png.checked)
// tf = true;
//else
// tf = false;
drawRightY();
}
function drawRightY() {
tf = false;
var valori = GetCellValues();
var f = new Array();
for (var i=0;i<valori.rows.length;i++) {
f[i]=new Array();
for (var j=0;j<valori.rows[i].cells.length;j++) {
f[i][j]= valori.rows[i].cells[j].innerHTML;
}
}
var data = new google.visualization.arrayToDataTable(f,true);
var options = {
chart: {
// title: z,
},
hAxis: {
minValue: 0,
},
vAxis: {
},
axes: {
y: {
0: {side: 'right'}
}
}
};
if (tf == false){
var material = new google.visualization.BarChart(document.getElementById('chart_div'));
material.draw(data, options);
}
if (tf == true) {
var chart_div = document.getElementById('chart_div');
var chart = new google.visualization.BarChart(chart_div);
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(chart, 'ready', function () {
chart_div.innerHTML = '<img src="' + chart.getImageURI() + '">';
console.log(chart_div.innerHTML);
});
options = {width: 1920, height: 1080}
chart.draw(data, options);
document.getElementById("chart_div").style.display="none";
window.open(chart.getImageURI());
}
}
<HTML>
<HEAD>
<TITLE>Modifying Table Cell Content</TITLE>
<STYLE TYPE="text/css">
THEAD {background-color:lightyellow; font-weight:bold}
TFOOT {background-color:lightgreen; font-weight:bold}
#myTABLE {background-color:bisque}
</STYLE>
<SCRIPT src="funzioni.js"></SCRIPT>
<SCRIPT type="text/javascript" src="https://www.google.com/jsapi"></SCRIPT>
<SCRIPT type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawRightY());
</SCRIPT>
</HEAD>
<BODY onLoad="init(),nascondi()">
<H1>Modifying Tables</H1>
<HR>
<FORM NAME="controls">
<FIELDSET>
<LEGEND>Add/Remove Rows</LEGEND>
<TABLE WIDTH="100%" CELLSPACING=20><TR>
<TD><INPUT TYPE="button" VALUE="Append 1 Row"
onClick="appendRow(this.form)"></TD>
<TD><INPUT TYPE="button" VALUE="Insert 1 Row" onClick="addRow(this.form)"> at index:
<SELECT NAME="insertIndex">
<OPTION VALUE="0">0
</SELECT></TD>
<TD><INPUT TYPE="button" NAME="removeRowBtn" VALUE="Delete 1 Row" DISABLED
onClick="removeRow(this.form)"> at index:
<SELECT NAME="deleteIndex">
<OPTION VALUE="0">0
</SELECT></TD>
</TR>
</TABLE>
</FIELDSET>
<FIELDSET>
<LEGEND>Add/Remove THEAD and TFOOT</LEGEND>
<TABLE WIDTH="100%" CELLSPACING=20><TR>
<TD><INPUT TYPE="button" NAME="addTHEAD" VALUE="Insert THEAD"
onClick="insertTHEAD(this.form)"><BR>
<INPUT TYPE="button" NAME="deleteTHEAD" VALUE="Remove THEAD" DISABLED
onClick="removeTHEAD(this.form)">
</TD>
<TD><INPUT TYPE="button" NAME="addTFOOT" VALUE="Insert TFOOT"
onClick="insertTFOOT(this.form)"><BR>
<INPUT TYPE="button" NAME="deleteTFOOT" VALUE="Remove TFOOT" DISABLED
onClick="removeTFOOT(this.form)">
</TD>
</TR>
</TABLE>
</FIELDSET>
<FIELDSET>
<LEGEND>Add/Remove Caption</LEGEND>
<TABLE WIDTH="100%" CELLSPACING=20><TR>
<TD><INPUT TYPE="button" NAME="addCaption" VALUE="Add Caption"
onClick="insertCaption(this.form)"></TD>
<TD>Text: <INPUT TYPE="text" NAME="captionText" SIZE=40 VALUE="Sample Caption">
<TD><INPUT TYPE="button" NAME="deleteCaption" VALUE="Delete Caption" DISABLED
onClick="removeCaption(this.form)"></TD>
<TD><INPUT TYPE="button" NAME="Prendi valori" VALUE="get"
onClick="GetCellValues()"></TD>
</TR>
</TABLE>
</FIELDSET>
<!-- PNG<input type="checkbox" id="png" value="false" />-->
<input type="button" value="Draw Chart" onclick="mostra(),setDati()" />
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</FORM>
<HR>
<TABLE ID="myTABLE" CELLPADDING=10 BORDER=1>
<TBODY>
</TABLE>
</BODY>
</HTML>

You should try to narrow down your questions and post only related code.
The problem you have is you're not converting your HTML Table values from strings to numbers when you add the values from the table to your "dataArray", which causes the whole input to try to represent strings with numbers.
I modified your array building loop, and added if(i > 0) (if it's not the first row (the headings) anymore). Whole loop now looks like:
for (var i=0;i<valori.rows.length;i++) {
f[i]=new Array();
for (var j=0;j<valori.rows[i].cells.length;j++) {
if(i > 0){
f[i][j]= Number(valori.rows[i].cells[j].innerHTML);
}else{
f[i][j]= valori.rows[i].cells[j].innerHTML;
}
}
}
and it now works like a charm.
Link to jsfiddle.

Related

Copy textbox value to another textbox inside dynamic table

I have a textbox where users input the owner's name and I want to copy it automatically or on button click on a textbox inside my dynamic table. How can I possibly do it using javascript? I needed the exact copy of the inputted value on the first textbox to be the value of the textbox inside the dynamic table. Please help
window.onload = function() {
var ModelArray = {
"Mammals": {
"Dog": {
"Dog Food": ["Milk"]
},
"Cat": {
"Cat food": ["Milk"]
},
"Tiger": {
"Meat": ["Water"]
},
"Monkey": {
"Banana": ["Water"]
}
},
"Reptiles": {
"Snake": {
"Rat": ["None"]
},
"Turtle": {
"Plant": ["Water"]
},
"Lizard": {
"Insects": ["None"]
},
"Crocodile": {
"Meat": ["Water"]
}
}
}
//Get html elements
var model = document.getElementById("MODEL");
var destination = document.getElementById("destination");
var criteria = document.getElementById("criteria");
var material_form = document.getElementById("material_form");
//load models
for (var model_value in ModelArray) {
model.options[model.options.length] = new Option(model_value, model_value);
}
//model changed -> destination value
model.onchange = function() {
destination.length = 1;
criteria.length = 1;
material_form.length = 1;
if (this.selectedIndex < 1) {
criteria.options[0].text = ""
return;
}
destination.options[0].text = "Select Animal..."
for (var destination_value in ModelArray[this.value]) {
destination.options[destination.options.length] = new Option(destination_value, destination_value);
}
if (destination.options.length == 2) {
destination.selectedIndex = 1;
destination.onchange();
}
}
//destination changed -> criteria value
model.onchange();
destination.onchange = function() {
criteria.length = 1;
material_form.length = 1;
if (this.selectedIndex < 1) {
criteria.options[0].text = ""
return;
}
criteria.options[0].text = ""
for (var criteria_value in ModelArray[model.value][this.value]) {
criteria.options[criteria.options.length] = new Option(criteria_value, criteria_value);
}
if (criteria.options.length == 2) {
criteria.selectedIndex = 1;
criteria.onchange();
}
}
//criteria changed -> material form value
criteria.onchange = function() {
material_form.length = 1;
if (this.selectedIndex < 1) {
material_form.options[0].text = ""
return;
}
material_form.options[0].text = ""
var material_form_value = ModelArray[model.value][destination.value][this.value];
for (var i = 0; i < material_form_value.length; i++) {
material_form.options[material_form.options.length] = new Option(material_form_value[i], material_form_value[i]);
}
if (material_form.options.length == 2) {
material_form.selectedIndex = 1;
// material_form.onchange();
}
}
}
function SaveData() {
var DataList = [];
var table = document.getElementById("bod");
var rowLength = table.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++) {
//gets cells of current row
var oCells = table.rows.item(i).cells;
//gets amount of cells of current row
//var cellLength = oCells.length-2;
//loops through each cell in current row
var item = {};
item["destination"] = oCells.item(0).innerHTML;
item["criteria"] = oCells.item(1).innerHTML;
item["material"] = oCells.item(2).innerHTML;
DataList.push(item)
}
var request = new XMLHttpRequest()
request.open("POST", "DOM_SAVE.php", true)
request.setRequestHeader("Content-type", "application/json")
request.send(JSON.stringify(DataList));
console.log(DataList);
}
function addRow() {
var table = document.getElementById("bod");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.insertCell(0).innerHTML = destination.value;
row.insertCell(1).innerHTML = criteria.value;
row.insertCell(2).innerHTML = material_form.value;
row.insertCell(3).innerHTML = '<input type ="button" value="Delete" onClick="Javacsript:deleteRow(this)">';
row.insertCell(4).innerHTML = '<input type ="text" name = "owner">';
}
function deleteRow(obj) {
var index = obj.parentNode.parentNode.rowIndex;
var table = document.getElementById("myTableData");
table.deleteRow(index);
}
Owner: <input type="text" name="field10" id="field10" readonly="true" />
<td><b>MODEL: </b></td>
<td>
<select id="MODEL" NAME="MODEL" size="1" required>
<option value="" selected="selected">Select Model...</option>
</select>
</td>
<b>DESTINATION: </b></td>
<tr>
<td>
<select ID="destination" NAME="destination[]" required>
<option value="" selected="selected">Select Model First...</option>
</select>
<select ID="criteria" NAME="criteria[]" contenteditable="true" required>
</select>
<select ID="material_form" NAME="material_form[]" required>
</select>
<input type="button" id="add" value="Add Destination" onclick="Javascript:addRow()">
</td>
</tr>
</center>
<div id="mydata" style="text-align: center">
<center>
<table id="myTableData" border="1" style="text-align:center;"><br>
<thead>
<tr>
<td style="padding: 0 10px 0 10px"><b>DESTINATION</b></td>
<td style="padding: 0 10px 0 10px"><b>CRITERIA</b></td>
<td style="padding: 0 10px 0 10px"><b>MATERIAL FORM</b></td>
<td style="padding: 0 10px 0 10px"><b>.............</b></td>
<td style="padding: 0 10px 0 10px"><b>Owner Name</b></td>
</tr>
</center>
</thead>
<tbody id="bod">
</tbody>
</table>
</div><br>
<center>
<input type="submit" name="submit" value="Submit">
Yes you can. I know the question is dated, but hope it will help future searchers.
Using javascript you can copy value from one textbox to another:
HTML:
<input type='text' onblur="sync()" id='from'/>
<input type='text' id='to'/>
Javascript
<script type="text/javascript">
function sync() {
src = document.getElementById("from");
dest = document.getElementById("to");
dest.value = src.value;
}
</script>

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>

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.

JavaScript: Why is the new dropdown not being filled with values

Here is my code:
<script language="javascript">
var counter =0,temp,m,cloneNodem;
function getVtierDefList(){
var vtierDefList = var vtierDefList = [{"label":"d1nis1w20","value":"28914"},{"label":"d1nis1m13","value":"28915"},{"label":"d1nis2d9","value":"28661"},{"label":"d1nis3d1","value":"28916"},{"label":"d1nis1a1","value":"27238"},{"label":"d1nis1a13","value":"28917"},{"label":"s2nis1d0","value":"28660"},{"label":"s2nis1a0","value":"28659"},{"label":"t3nis1d0","value":"27237"}];;
return vtierDefList;
}
</script>
</head>
<body onload="load();">
<div id="doc">
<div id="main">
<table id="vtier#1">
<tr>
<td><button onclick="delVtier(this);return false;" /></td>
<td>1.Vtier Name: <select id="vtier" name="vtierSelect" onchange="doAjax(this);return false;">
<option selected="selected" value="-1">Any</option>
</select></td>
</tr>
</table>
<div id="accountarea" >
</div>
</div>
</div>
<div id="plus"><button onclick="addVtier();return false;"/></div>
</body>
</html>
<script language="javascript">
function addVtier() {
m = document.getElementById("main");
cloneNodem = m.cloneNode(true);
temp = cloneNodem.cloneNode(true);
document.getElementById("main").appendChild(temp);
counter++;
fillDropDown(counter);
}
function load() {
var vtierSelectedList = document.getElementsByName("vtierSelect");
addDropDownValues(getVtierDefList(), vtierSelectedList[0],"-1");
}
function addDropDownValues(Elements,DropDwn,SelectID)
{ if(DropDwn.options){
DropDwn.options.length = 1
}
for(var i=0;i<Elements.length;i++)
{
var addOption = new Option();
addOption.value = Elements[i].value;
addOption.innerHTML = Elements[i].label;
if(addOption.value == SelectID)addOption.selected = true;
DropDwn.appendChild(addOption);
}
}
function fillDropDown(dropDwn) {
var vtierSelectedList = document.getElementsByName("vtierSelect");
vtierSelectedArray = new Array(vtierSelectedList.length);
var vtierDefList = getVtierDefList();
for(var k=0;k<vtierSelectedList.length;k++) {
vtierSelectedArray[k] =vtierSelectedList[k].options[vtierSelectedList[k].selectedIndex].value ;
}
var diff = diffArray(getVtierDefList(), vtierSelectedArray);
addDropDownValues(diff,vtierSelectedList[dropDwn],"-1");
}
// this function diffArray just finds the difference between the two arrays
function diffArray(a, b) {
var seen = [], diff = [];
for ( var i = 0; i < b.length; i++)
seen[b[i]] = true;
for ( var i = 0; i < a.length; i++)
if (!seen[a[i].value])
diff.push(a[i]);
return diff;
}
</script>
Now my question is when this code fills the dropdown list for the first dropdown why does it not fill the dropdown list for the subsequent dropdowns with the new calculated array not having the already selected elements in the dropdowns boxes ?
One possible problem is in how you're adding options to your select. Instead of this:
DropDwn.appendChild(addOption);
Opt for this:
DropDwn.options.add(new Option(Elements[i].label, Elements[i].value));
Your select has an id, so instead of
var vtierSelectedList = document.getElementsByName("vtierSelect");
addDropDownValues(getVtierDefList(), vtierSelectedList[0],"-1");
Just select this element by id:
var vtierSelectedList = document.getElementsById("vtier");
addDropDownValues(getVtierDefList(), vtierSelectedList,"-1");

Categories

Resources