Copy textbox value to another textbox inside dynamic table - javascript

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>

Related

How do I display a dynamically created html table only once?

Each time I input another football score, the league table is updated and displayed but it's appended to a list of tables. How do I display only the latest table?
Here is an extract of the html:
<div>
<table id="matches" border="1"> </table>
</div>
<div>
<table id="standings" border="1"> </table>
</div>
<input type="button" value="Update" onclick="update()" />
Here is the javascript that displays the fixtures for inputting scores:
// Display fixtures to input the scores
window.onload = function()
{
table = document.getElementById("matches");
var row;
var cell1;
var cell2;
var cell3;
for (i = 1; i < Results.length; i++)
{
row = table.insertRow(i-1); //table starts row 0 but Results row 1 so i-1 used
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell4 = row.insertCell(3);
cell1.innerHTML = Results[i][0];
cell2.innerHTML = '<input type="number" min="0" max="99"/>'
cell3.innerHTML = '<input type="number" min="0" max="99"/>'
cell4.innerHTML = Results[i][3];
}
}
And here is the code that displays the table after the lastest scores have been inputed:
// Display League Table
standings = document.getElementById("standings");
for (i = 0; i < League.length; i++)
{
row = standings.insertRow(i);
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell4 = row.insertCell(3);
cell5 = row.insertCell(4);
cell6 = row.insertCell(5);
cell7 = row.insertCell(6);
cell8 = row.insertCell(7);
cell1.innerHTML = League[i][0];
cell2.innerHTML = League[i][1];
cell3.innerHTML = League[i][2];
cell4.innerHTML = League[i][3];
cell5.innerHTML = League[i][4];
cell6.innerHTML = League[i][5];
cell7.innerHTML = League[i][6];
cell8.innerHTML = League[i][7];
}
After entering three scores this is what is displayed:
I've tried clearing the league array within javascript but still the same outcome. How do I only display top version of the table? Thanks
Thanks again to comments, and some further googling, the following deletes the table ahead of updating it, unless there's a better way?
for(var i = standings.rows.length - 1; i >= 0; i--)
{
standings.deleteRow(i);
}
Cheers everyone! :)
For your table update/question, focus on the updateRow function. This line does the actual update of contents of row rownum column(<td>) i
rows[rownum].getElementsByTagName('td')[i].innerHTML = coldata[i];
There is more here than just updating the table rows, for that you can review the function updateRow in my name-spaced object. updateRow calls createRow if it needs to (the row at that index does not exist), nothing fancy here, then updates the new row.
I use the array of match objects in matches I created (was not one in the question so I made assumptions) also in the namespace:
matches: [{
match: 1,
score: [{
team: "Ap",
score: 3
}, {
team: "Or",
score: 2
}]
}],
Note where I call this code to update the table for standings in the table with standings-table id. I have no idea what those are so I simply inserted some stuff in the array then update the table using
for (let i = 0; i < myLeague.standings.length; i++) {
myLeague.updateRow('standings-table', myLeague.standings[i], i);
}
Other things: I created the form simply to show how to update the table when a new match is inserted, I trigger an event and it does what it needs to update or insert a row - but really that is just to test the update as new matches are created.
Row in a table are either updated or inserted depending totally on the array of matches content
nothing handles deletions from the table or array since this was just about insert and update
if a row index for a match index does not exist, it creates a new row and updates it
var myLeague = myLeague || {
teamSelect1: "team1",
teamSelect2: "team2",
matchesPlayed: 1,
teams: [{
name: "Apples",
abbreviation: "Ap"
},
{
name: "Oranges",
abbreviation: "Or"
},
{
name: "Pears",
abbreviation: "Pe"
}
],
matches: [{
match: 1,
score: [{
team: "Ap",
score: 3
}, {
team: "Or",
score: 2
}]
}],
standings: [
["A", 2, 1, 1, 3, 2, 3, 0],
["B", 3, 1, 1, 3, 2, 3, 6]
],
cloneRow: function(tableid, objectRef) {
// find table to clone/append to
let table = document.getElementById(tableid);
// find row to clone, I use first one
let firstRow = mytable.rows[0];
// let row = document.getElementById("rowToClone");
let clone = firstRow.cloneNode(true); // copy children too
clone.id = ""; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
},
createRow: function(tableid, colCount, rowCount = 1, defaultContent = "") {
let row = document.createElement('tr'); // create row node
for (let i = 0; i < colCount; i++) {
let newText = document.createTextNode(defaultContent);
let col = row.insertCell(i);
col.appendChild(newText);
}
let table = document.getElementById(tableid); // find table to append to
let tbody = table.getElementsByTagName('tbody')[0];
for (let r = 1; r <= rowCount; r++) {
tbody.appendChild(row); // append row to table
}
},
updateRow: function(tableid, coldata = ['$nbsp;'], rownum = 0) {
let table = document.getElementById(tableid); // find table to update to
let tbody = table.getElementsByTagName('tbody')[0];
let rows = tbody.rows; // get rows node
let maxRows = 20; //keep it from going crazy adding rows
while (rows.length < maxRows && !rows[rownum]) {
this.createRow(tableid, coldata.length, 1, "x");
}
//myLeague.updateRow(tableid,coldata, rownum);
for (let i = 0; i < coldata.length; i++) {
rows[rownum].getElementsByTagName('td')[i].innerHTML = coldata[i];
}
},
addTeam: function(team, teamid) {
var sel = document.getElementById(teamid);
var optNew = document.createElement("option");
optNew.value = team.abbreviation;
optNew.text = team.name;
sel.add(optNew, null);
},
addTeamsToSelect: function() {
myLeague.teams.forEach(function(team) {
myLeague.addTeam(team, this.teamSelect1);
myLeague.addTeam(team, this.teamSelect2);
}, this);
},
listMatches: function(event) {
// event.target is the div
let src = event.target.dataset.source;
console.log("src:", src);
document.getElementById("matchplayed").textContent = event.matches;
this[src].forEach(function(item, index, array) {
document.getElementById('matchplayed').textContent = array.length;
let rowdata = [item.score[0].team, item.score[0].score, item.score[1].team, item.score[1].score];
this.updateRow(src, rowdata, index);
}, this);
},
clickAddListener: function(event) {
// 'this' is bound to the namespace object
// console.log(event.target); // the button
// console.log(this.matchesPlayed);//namespace
if (!document.getElementById(this.teamSelect1).value || !document.getElementById(this.teamSelect2).value) {
let errorEl = document.getElementById("form1")
.getElementsByClassName("error-text")[0];
errorEl.textContent = "Both teams need to be selected.";
errorEl.style.visibility = 'visible';
errorEl.style.opacity = '1';
setTimeout(function() {
errorEl.style.WebkitTransition = 'visibility .5s, opacity .5s';
errorEl.style.opacity = '0';
errorEl.style.visibility = 'hidden';
errorEl.textContent = "";
}, 5000);
} else {
this.matchesPlayed++;
let r = {
match: this.matchesPlayed,
score: [{
team: document.getElementById(this.teamSelect1).value,
score: document.getElementById("score1").value
}, {
team: document.getElementById(this.teamSelect2).value,
score: document.getElementById("score2").value
}]
};
this.matches.push(r);
}
document.getElementById('matches').dispatchEvent(this.showmatchesevent);
},
addListeners: function() {
let scope = this;
document.getElementById(this.teamSelect1)
.addEventListener('change', function() {
let s = document.getElementById(scope.teamSelect2);
let oval = s.value;
if (this.value == oval) {
s.value = '';
}
}, this);
document.getElementById(this.teamSelect2)
.addEventListener('change', function() {
let s = document.getElementById(scope.teamSelect1);
let oval = s.value;
if (this.value == oval) {
s.value = '';
}
}, this);
document.getElementById('add-match')
// bind this namespace to the event listener function
.addEventListener('click', (this.clickAddListener).bind(this), false);
this.showmatchesevent = new CustomEvent('showmatches');
document.getElementById('matches')
.addEventListener('showmatches', this.listMatches.bind(this), false);
}
};
window.onload = function() {
myLeague.addTeamsToSelect();
myLeague.addListeners();
for (let i = 0; i < myLeague.standings.length; i++) {
myLeague.updateRow('standings-table', myLeague.standings[i], i);
}
// set table from defaults/imported list
document.getElementById('matches').dispatchEvent(myLeague.showmatchesevent);
};
/* typography */
html {
font-family: 'helvetica neue', helvetica, arial, sans-serif;
}
th {
letter-spacing: 2px;
}
td {
letter-spacing: 1px;
}
tbody td {
text-align: center;
}
.match-inputs {
border: solid 2px #DDDDDD;
padding;
1em;
margin: 1em;
}
.error-text {
height: 1em;
color: red;
}
.matches-played {
padding: 13m;
}
/* table layout */
table {
border-collapse: collapse;
border: 1px solid black;
}
.score th,
td {
padding: 0.2em;
border: solid #DDDDDD 1px;
}
.container {
padding: 1em;
}
<div class="container match-inputs">
<form id="form1">
<div>Add Matches</div>
<div class="input-group"><label>Choose L Team:</label>
<select id="team1">
<option value="">Choose</option>
</select>
</div>
<div class="input-group"><label>Choose L2 Team:</label>
<select id="team2">
<option value="">Choose</option>
</select>
</div>
<div class="input-group score-group"><label>Team1 score:</label>
<input id="score1" type="number" class="score-input" value="0" min="0" max="99" value="0" />
</div>
<div class="input-group score-group"><label>Team2 score:</label>
<input id="score2" type="number" class="score-input" value="0" min="0" max="99" value="0" />
</div>
<div class="input-group"><label>Add this match to the list.</label>
<button type="button" id="add-match">Add Match</button>
</div>
<div class="error-text"> </div>
</form>
</div>
<div class="container">
<div class="matches-played">Matches Played:<span id="matchplayed"></span></div>
<table id="matches" data-source="matches">
<thead>
<tr>
<th colspan="4">Matches</th>
</tr>
<tr>
<th>L</th>
<th>S</th>
<th>S2</th>
<th>L1</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>
<div class="container">
<table id="standings-table">
<thead>
<tr>
<th colspan="8">Standings</th>
</tr>
<tr>
<th>Team</th>
<th>P</th>
<th>W</th>
<th>D</th>
<th>L</th>
<th>F</th>
<th>A</th>
<th>Pts</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</div>

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.

How to get values from option-list into consecutive input-fields by onclick-function

I have a html-form to read out data from a database.
By clicking a button, there is the possibility to create additional input fields.
<table>
<tr>
<td>
<input type="text" id="productinput" name="productinput[]" class="awesomplete" list="productselect" size="20"/>
</td>
</tr>
<tr>
<td>
<input type="text" id="productinput2" name="productinput[]" class="awesomplete" list="productselect" size="20"/>
</td>
</tr>
<tr>
<td>
<input type="text" id="productinput3" name="productinput[]" class="awesomplete" list="productselect" size="20"/>
</td>
</tr>
</table>
<script>
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
// Create new div
var newdiv = document.createElement('div');
newdiv.innerHTML = '<br><input type="text" name="productinput[]" class="awesomplete" list="productinputselect" size="20"/>';
document.getElementById(divName).appendChild(newdiv);
// Re instantiate Awesomplete
new Awesomplete(newdiv.querySelector('input'), { list: document.querySelector('#productinputselect') });
// Set counter
counter++;
}
}
</script>
<div id="dynamicInput">
<b></b><input type="text" id="productinput4" name="productinput[]" class="awesomplete" list="productinputselect" size="20"/>
</div>
<input type="button" value="Additional Input Field" onClick="addInput('dynamicInput');">
<select name="productselect" id="productselect" size="9" onclick="sendproductnameinput()">
<?php
include("../files/zugriff.inc.php"); // database access
$sql = "SELECT * FROM product_main ORDER BY Name";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo '<option class="optproduct" value='. $row['Name'] . '>' . $row['Name']. '</option>';
echo '<br>';
}
mysqli_close($db);
?>
</select>
So far, this works fine!
By using the following javascript-function the selected value from the -list is displayed in the first input-field.
function sendproductnameinput() {
document.formdatabase.productinput.value = document.formdatabase. productselect.value;
}
How can I get the next selected value in the second input-field and so on? This function should work in the additionally added fields, too.
You can use this :
for (var i = document.formdatabase.length - 1; i >= 0; i--) {
document.formdatabase[i].value = document.formdatabase.productselect.value;
}
Your Select seems to be not Multiple select, so I suppose you want to put the same selected value in each input.
And if multiple select than you can use this:
function getSelectValues(select) {
var result = [];
var options = select && select.options;
var opt;
for (var i=0, iLen=options.length; i<iLen; i++) {
opt = options[i];
if (opt.selected) {
result.push(opt.value || opt.text);
}
}
return result;
}
function sendproductnameinput() {
var selected = getSelectValues(document.formdatabase.productselect);
for (var i = document.formdatabase.length - 1; i >= 0; i--) {
if(i < selected.length) {
document.formdatabase[i].value = selected[i];
}
}
}
here is a fiddle https://jsfiddle.net/586menbv/16/
Well, it depends on where the function sendproductnameinput() is defined, but if the variable counter is visible from it's scope, I would dare to write something like this:
var timesSomethingSelected = 1;
function sendproductnameinput() {
var productinput = 'productinput';
if(timesSomethingSelected > 1) {
productinput += timesSomethingSelected;
timesSomethingSelected++;
} else if(timesSomethingSelected == counter) {
//Do something if there aren't more inputs.
}
document.formdatabase[productinput].value = document.formdatabase. productselect.value;
}

Get values from dynamic table and draws it with google charts

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.

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