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

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

Related

Shopping Cart Update Total Function doesnt work

I am building an eCommerce store website, and I am facing an issue. The function updateCartTotal doesn't work at all. The script is also added to the bottom of the HTML body.
Thanks in advance.
HTML:
<span class="material-symbols-outlined" id="cart-icon">
shopping_cart
</span>
<div class="cart">
<h2 class="cart-title">Your Shopping Cart</h2>
<div class="cart-content">
<div class="cart-box">
<img src="/Monn-Homme/images/tie1.jpg" class="cart-image">
<div class="detail-box">
<div class="cart-product-title">
Tie
</div>
<div class="cart-price"> £10.99</div>
<input type="number" value="1" class="cart-qty">
</div>
<span class="material-symbols-outlined" id="cart-remove">
delete
</span>
</div>
</div>
<div class="total">
<div class="total-title">Total</div>
<div class="total-price">£10.99</div>
</div>
<button type="button" class="buy-btn">Buy Now</button>
<span class="material-symbols-outlined" id="close-cart">
close
</span>
</div>
</div>
Javascript:
let cartIcon = document.getElementById("cart-icon");
let cart = document.querySelector(".cart");
let CloseCart = document.querySelector("#close-cart");
cartIcon.onclick = () => {
cart.classList.add("active");
};
CloseCart.onclick = () => {
cart.classList.remove("active");
};
if (document.readyState == "loading") {
document.addEventListener("DOMContentLoaded", ready);
} else {
ready();
}
function ready() {
var removeCartButtons = document.getElementsByClassName("material-symbols-outlined");
for (var i = 0; i < removeCartButtons.length; i++) {
var button = removeCartButtons[i];
button.addEventListener("click", removeCartItem)
}
// Quantity Change //
var quantitInputs = document.getElementsByClassName("cart qty");
for (var i = 0; i < quantitInputs.length; i++) {
var input = quantitInputs[i];
input.addEventListener("change", quantityChanged);
}
}
function removeCartItem(event) {
var buttonClicked = event.target;
buttonClicked.parentElement.remove();
updateCartTotal();
}
quantityChanged = (event) => {
var input = event.target;
if (isNaN(input.value) || input.value <= 0) {
input.value = 1;
}
updateCartTotal();
}
function updateCartTotal() {
var cartContainer = document.getElementsByClassName("cart-content")[0];
var cartBox = cartContainer.getElementsByClassName("cart-box");
var total = 0
for (var i = 0; i < cartBox.length; i++) {
var cartBox = cartBox[i]
var priceElement = cartBox.getElementsByClassName("cart-price")[0]
var quantityElement = cartBox.getElementsByClassName("cart-qty")[0]
price = parseFloat(priceElement.innerText.replace("£", ""))
quantity = quantityElement.value
total = total + (price * quantity)
}
document.getElementsByClassName("total-price")[0].innerText = total
}
i am expecting the total to update as the quantity changes, and the function to work
You have the following mistakes-
There is no element with the class name cart qty.
var quantitInputs = document.getElementsByClassName("cart qty");
quantityChanged function should have a function keyword.
You are using the same name variable cartBox in updateCartTotal function which is creating confusion-
var cartBox = cartContainer.getElementsByClassName("cart-box");
for (var i = 0; i < cartBox.length; i++) {
var cartBox = cartBox[i]
}
Now, after fixing these mistakes, your code will look like the below which is working.
Note- I moved all the declarations to the top and I replaced those two methods-
getElementsByClassName() = querySelectorAll()
getElementsByClassName()[0] = querySelector()
let cartIcon = document.querySelector("#cart-icon");
let cart = document.querySelector(".cart");
let CloseCart = document.querySelector("#close-cart");
var quantitInputs = document.querySelectorAll(".cart-qty");
var removeCartButtons = document.querySelectorAll(".material-symbols-outlined");
var cartContainer = document.querySelector(".cart-content");
var cartBox = cartContainer.querySelectorAll(".cart-box");
var totalEl = document.querySelector(".total-price")
cartIcon.onclick = () => {
cart.classList.add("active");
};
CloseCart.onclick = () => {
cart.classList.remove("active");
};
if (document.readyState == "loading") {
document.addEventListener("DOMContentLoaded", ready);
} else {
ready();
}
function ready() {
for (var i = 0; i < removeCartButtons.length; i++) {
var button = removeCartButtons[i];
button.addEventListener("click", removeCartItem);
}
// Quantity Change //
for (var i = 0; i < quantitInputs.length; i++) {
var input = quantitInputs[i];
input.addEventListener("change", quantityChanged);
}
}
function removeCartItem(event) {
var buttonClicked = event.target;
buttonClicked.parentElement.remove();
updateCartTotal();
}
function quantityChanged(event) {
var input = event.target;
if (isNaN(input.value) || input.value <= 0) {
input.value = 1;
}
updateCartTotal();
};
function updateCartTotal() {
var total = 0;
for (var i = 0; i < cartBox.length; i++) {
var cartBoxEl = cartBox[i];
var priceElement = cartBoxEl.querySelector(".cart-price");
var quantityElement = cartBoxEl.querySelector(".cart-qty");
price = parseFloat(priceElement.innerText.replace("£", ""));
quantity = quantityElement.value;
total = total + price * quantity;
}
if (totalEl) {
totalEl.innerText = total;
}
}
<div>
<span class="material-symbols-outlined" id="cart-icon">
shopping_cart
</span>
<div class="cart">
<h2 class="cart-title">Your Shopping Cart</h2>
<div class="cart-content">
<div class="cart-box">
<img src="/Monn-Homme/images/tie1.jpg" class="cart-image">
<div class="detail-box">
<div class="cart-product-title">
Tie
</div>
<div class="cart-price"> £10.99</div>
<input type="number" value="1" class="cart-qty">
</div>
<span class="material-symbols-outlined" id="cart-remove">
delete
</span>
</div>
</div>
<div class="total">
<div class="total-title">Total</div>
<div class="total-price">£10.99</div>
</div>
<button type="button" class="buy-btn">Buy Now</button>
<span class="material-symbols-outlined" id="close-cart">
close
</span>
</div>
</div>

Get Elements of a HTML div

i am building a configuration utility and having a problem with the js.
I am very new to javascript so i apologize in advance for the request for help.
in my HTML i have multiple divs that are structured like this:
<div id="options" class="opt">
<h2 id="optionName">Power Button Options</h2>
<label for="pwrAvl">Power Button Available</label>
<input type="checkbox" name="pwrAvl" id="pwrAvl"/ >
<br /><br />
<label for="pwrLabel">Power Button Label</label>
<input type="text" name="pwrLabel" id="pwrLabel"/ >
<br /><br />
<label for="pwrGraphic">Power Button Graphic</label>
<select name="pwrGraphic" id="pwrGraphic">
<option value="" selected>
----- Please select a graphic -----
</option>
<option value="power.jpeg">Power</option>
<option value="light.jpg">Light</option>
<option value="help.jpg">Help</option>
<option value="camera.jpg">Camera</option>
</select>
<br /><br />
<label for="pwrIndex">Power Button Menu Index</label>
<input type="text" name="pwrIndex" id="pwrIndex"/ >
</div>
i have between 5-10 divs that will all be structured the same way just with different labels and input values.
i tried adding all the divs to an array and then enumerate through the array but that did not work.
here is my js file what i have tried:
{
const bar = document.querySelector('options');
var opts = document.querySelectorAll('.opt')
var option = {}
var nCount = $(".opt").length;
var divArray = [];
var optName = document.getElementById('optionName');
function addArray() {
for (let i = 0; i < nCount; i++) {
divArray[i] = opts[i];
}
}
const saveBtn = document.getElementById('submit');
saveBtn.addEventListener('click', (e) => {
putSettings();
});
function SystemOptions(optionName, optionAvailable, optionLabel, optionGraphic, optionIndex) {
this.optionName = optionName;
this.optionAvailable = optionAvailable;
this.optionLabel = optionLabel;
this.optionGraphic = optionGraphic;
this.optionIndex = optionIndex;
}
async function putSettings() {
let info = {
"SystemConfiguration": {
"Options": [],
}
}
addArray()
console.log(`Divarray = ${divArray.length}`)
//The following would never work
opts.forEach(label => {
$('[id=optionName]').each(function () {
var atId = this.id;
console.log(`Searched Name = ${atId.innerHTML}`)
});
});
divArray.forEach(element => {
var name = divArray.getElementById('optionName').innerHTML;
console.log(name)
option = new SystemOptions(name, "yes", "Help Label", "Option.jpeg", 3);
info.SystemConfiguration.Options.push(option);
});
for (let i = 0; i < nCount; i++) {
// console.log(` ${$(".opt").find("h2[id=optionName").each.text()}`)
console.log(` ${divArray[i].querySelector(optName[i]).innerHTML}`)
}
// i did this once to see if the SystemsOptions function worked
// obviosly it added the same data 7 times but i was trying to be sure the function worked and created the json objects
for (let i = 1; i < nCount; i++) {
option = new SystemOptions("Power", "yes", "Help Label", "Option.jpeg", 3);
info.SystemConfiguration.Options.push(option);
}
let data = JSON.stringify(info, 0, 4);
console.log(data);
}
}
any help would be greatly appreciated.
not the most eloquent but this does work.
sure there are better ways:
var opts = document.querySelectorAll('.opt');
var option = {};
const saveBtn = document.getElementById('submit');
saveBtn.addEventListener('click', (e) => {
putSettings();
});
function SystemOptions(optionName, optionAvailable, optionLabel, optionGraphic, optionIndex) {
this.optionName = optionName;
this.optionAvailable = optionAvailable;
this.optionLabel = optionLabel;
this.optionGraphic = optionGraphic;
this.optionIndex = optionIndex;
}
async function putSettings() {
let info = {
"SystemConfiguration" :{
"Options": [],
}
};
for(var opt of opts)
{
var name = opt.getElementsByTagName('h2')[0].innerHTML;
let isAvailable = opt.getElementsByTagName("input")[0].value;
let optLabel = opt.getElementsByTagName("input")[1].value;
let optGraphic = opt.getElementsByTagName('select')[0].value;
let index = opt.getElementsByTagName("input")[2].value;
option = new SystemOptions(name, isAvailable, optLabel, optGraphic, index);
info.SystemConfiguration.Options.push(option);
}
console.log(`Number of options = ${opts.length}`)
let data = JSON.stringify(info, 0, 4);
console.log(data);
};

Display elemens of 2 arrays in <li>

And thanks in advance for looking into this, I am trying to show elements of 2 arrays in html (li) tags. This should be the format echoed out:
array1; array2
c201;100
c202;0
c450;320
......
The elements that will be pushed into the array are coming from input fields. I have created the following code and I get to see the correct format but when I copy and paste the values above, it loses the format and instead of having two columns, it pastes elements of array2 just below the elements of array1:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My Web Page</title>
<script>
var array_accounts = [];
var array_credits = [];
var x = 0;
var i = 0;
var z = 0;
function spara(){
var accounts_code_str = document.getElementById('accounts').value;
var accounts_code_comma = accounts_code_str.split(' ');
var accounts_code_comma = accounts_code_comma.join(';<br>');
array_accounts.push(accounts_code_comma);
console.log(array_accounts);
var iz_credits_str = document.getElementById('credits').value;
var iz_credits_comma = iz_credits_str.split(" ");
//var iz_credits_comma = iz_credits_comma.join('<br> ');
for(var z=0; z<iz_credits_comma.length; z++){
if(iz_credits_comma[z] < 0){
iz_credits_comma[z] = 0;
}
}
var iz_credits_comma = iz_credits_comma.join('<br> ');
array_credits.push(iz_credits_comma);
showAccounts();
showCredits();
}
</script>
</head>
<body>
<h1>Accounts and IZ credits</h1>
<div id="form">
<form>
<label>Insertar Accounts codes</label>
<input type="text" name="accounts" id="accounts" />
<label>Insertar Iz credits</label>
<input type="text" name="credits" id="credits" />
<input type ="button" onclick="spara()" value="Process data" />
</form>
</div>
<div id="codes" style="float:left">
<script>
function showAccounts(){
for (var x=0;x<array_accounts.length;x++){
document.write('<div style="float:left;">'+array_accounts[x]+';</div>');
}
}
</script>
</div>
<div id="credits" style="float:left">
<script>
function showCredits(){
for (var i=0;i<array_credits.length;i++){
document.write('<div style="float:left;">'+array_credits[i]+'<br></div>');
}
}
</script>
</div>
</body>
</html>
Many thanks in advance for your help!
Hope this helps!
<script>
var array_accounts = [];
var array_credits = [];
var x = 0;
var i = 0;
var z = 0;
function spara(){
var accounts_code_str = document.getElementById('accounts').value;
array_accounts = accounts_code_str.split(' ');
console.log(array_accounts);
var iz_credits_str = document.getElementById('credits').value;
var iz_credits_comma = iz_credits_str.split(" ");
array_credits=iz_credits_comma;
//var iz_credits_comma = iz_credits_comma.join('<br> ');
for(var z=0; z<iz_credits_comma.length; z++){
if(iz_credits_comma[z] < 0){
iz_credits_comma[z] = 0;
}
}
showAccounts();
}
function showAccounts(){
var ol = document.createElement("OL");
for (var x=0;x<array_accounts.length;x++){
var li = document.createElement("LI");
var textnode = document.createTextNode(array_accounts[x]+';'+array_credits[x]);
li.appendChild(textnode);
ol.appendChild(li)
}
document.getElementById("codes").appendChild(ol);
}
</script>
Modify the two javascript functions and that should do the trick! Thanks.

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.

Push value to array onclick and loop to add array values. Javascript

So i am pretty new at this and want to be able to add a dollar to the "deposit" text box every time I click the button. I'm going to have to do this with a quarter, dime, and nickel, button as well. This is what I have so far.
<input type="button" value="Dollar" id="dollar" />
$<input type="text" id="deposit" />
And the javascript is:
var $ = function (id) { return document.getElementById(id); }
var item = [];
var total = 0;
for (i=0; i < item.length; i++){
total += item[i];
$("deposit").value = total;
}
$("dollar").onclick = item.push(1);
Whatever help you can give is much appreciated!
Don't you mean
Live Demo
var $ = function (id) { return document.getElementById(id); }
var add = function(fld,val) {
return (parseFloat(fld.value)+val).toFixed(2);
}
window.onload=function() {
$("dollar").onclick=function() {
$("deposit").value = add($("deposit"),1);
}
$("dime").onclick=function() {
$("deposit").value = add($("deposit"),.1);
}
$("nickel").onclick=function() {
$("deposit").value = add($("deposit"),.05);
}
$("refund").onclick = function() {
$("deposit").value = "0.00";
}
}
Try this:
HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#1.9.1" data-semver="1.9.1" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<input type="button" value="Dollar" id="dollar" />
$ <input type="text" id="deposit" />
</body>
</html>
JavaScript:
$(function() {
var item = [];
$("#dollar").click(function() {
item.push(1);
var total = 0;
for (var i = 0; i < item.length; i++) {
total += item[i];
$("#deposit").val(total);
}
});
});
Plunker example

Categories

Resources