How do I add button values when the buttons have an array of values?

I wouldn’t say so. Just compare button.value against your string of numbers instead.

But why compare against numbers? The button could have a data value, that you can more easily use.

<button value="-1,1,0.7,0.7" data-type="insertCenter">

Then you can easily retrieve that from JavaScript:

if (button.dataset.type === "insertCenter") {
    ...
}

Which makes the code much more understandable than a bunch of mystery numbers.

I’ll try that on Monday. Thanks!

Assuming the values have been concatenated successfully and put in “cMount”, why doesn’t this OR work:
if (cMount === "-1,1,0.7,0.7" | "1,1,0.7,0.7") {

I think that you are working under an incorrect assumption.

The button value has the comma-separate values.
The getValues function converts those into an array of values.
The cMount variable is the array of values.
The cMount variable will never equal any string of numbers, because it’s not a string. It’s an array.
The cMount variable is the wrong variable for you to use.

Maybe you can set a string prop to button, like <button data-array="1,2,3,4" ></button>, every time you click, begin to calculate the result array, something like below:

function calculateButtonArray(event) {
  // here exist a previous string, infer the data of previous button you clicked
  const previousString = "1,2,3,4";
  const currButton = event.target || window.event.srcElement;
  const currString = currButton.getAttribute("data-array");
  return combineArray(currString.split(","), previousString.split(","));
}

function combineArray(arrA, arrB) {
  return arrA.map((a, index) => a + arrB[index]);
}

May it help you.

1 Like

I liked your approach to the OPs problem.
It finally made sense to me what the project’s purpose was about.

With that improved understanding, I created the follow TEST program
using the function (modified slightly) to create a simplified button calculator.
Nothing more than my attempt to understand the problem and incorporate 'fengxh’s interesting function.

<!DOCTYPE html><html lang="en"><head><title> Button Array Calculator </title>
<meta charset="UTF-8">
<meta name="viewport" content="width-device-width,initial-scale=1.0, user-scalable=yes"/>
<!--
 Idea from: https://www.sitepoint.com/community/t/how-do-i-add-button-values-when-the-buttons-have-an-array-of-values/351566/45 
-->

<style>
 legend { font-size: 1.5em; background-color: yellow; }
 button { width: 8em; font-size: 1.2em; }
 .add { background: lime; }
 .sub { background: pink; }
 .mul { background: cyan; }
 .div { background: orange; }
</style>
</head><body>

<fieldset id="btnTable"><legend>Button Array Calculator</legend>
 <button class="add" data-array="1,2,3,4">Add: 1,2,3,4</button>
 <button class="add" data-array="4,3,2,1">Add: 4,3,2,1</button>
 <button class="add" data-array="1,1,1,1">Add: 1,1,1,1</button>
 <button class="add" data-array="2,2,2,2">Add: 2,2,2,2</button><br>

 <button class="sub" data-array="1,2,3,4">Sub: 1,2,3,4</button>
 <button class="sub" data-array="4,3,2,1">Sub: 4,3,2,1</button>
 <button class="sub" data-array="1,1,1,1">Sub: 1,1,1,1</button>
 <button class="sub" data-array="2,2,2,2">Sub: 2,2,2,2</button><br>

 <button class="mul" data-array="1,2,3,4">Mul: 1,2,3,4</button>
 <button class="mul" data-array="4,3,2,1">Mul: 4,3,2,1</button>
 <button class="mul" data-array="2,2,2,2">Mul: 2,2,2,2</button>
 <button class="mul" data-array="3,3,3,3">Mul: 3,3,3,3</button><br>

 <button class="div" data-array="1,2,3,4">Div: 1,2,3,4</button>
 <button class="div" data-array="4,3,2,1">Div: 4,3,2,1</button>
 <button class="div" data-array="2,2,2,2">Div: 2,2,2,2</button>
 <button class="div" data-array="3,3,3,3">Div: 3,3,3,3</button>
</fieldset>

<button onclick="console.log('current results: ',accumulatorStr)">Results</button>
<button onclick="accumulatorStr='0,0,0,0';clrBtn()">Clear results</button>
<pre id='demo'></pre>

<script>
const doc = (IDS) => document.getElementById(IDS);
var former = console.log;  // retain former actions of console.log
console.log = function(...msg){
  former(...msg);  // maintains existing logging via the console. (optional)
  doc("demo").append(msg.join(' ')+'\n');  // output needs to be specified
} 
console.clear();
function btnClear(el) { while (el.firstChild) el.removeChild(el.firstChild); }
function clrBtn() { btnClear(doc('demo')); }

var accumulatorStr = '0,0,0,0';  // running calculations

function calculateButtonArray(event) {
  const previousString = accumulatorStr;
  const currButton = event.target || window.event.srcElement;
  const currString = currButton.getAttribute("data-array");

  var accumulator = [0,0,0,0]; // combineArray(currString.split(","), previousString.split(","));
  switch (event.className) {
    case 'add': accumulator = addArrays(currString.split(","), previousString.split(",")); break;
    case 'sub': accumulator = subArrays(currString.split(","), previousString.split(",")); break;
    case 'mul': accumulator = mulArrays(currString.split(","), previousString.split(",")); break;
    case 'div': accumulator = divArrays(currString.split(","), previousString.split(",")); break;
  }
  accumulatorStr = accumulator.join(',');  //  return accumulator;
  return accumulatorStr;
}

// different mathematical processes on button arrays
function addArrays(arrB, arrA) { return arrA.map( (a, index) => Number(a) + Number(arrB[index]) ); }
function subArrays(arrB, arrA) { return arrA.map( (a, index) => Number(a) - Number(arrB[index]) ); }
function mulArrays(arrB, arrA) { return arrA.map( (a, index) => Number(a) * Number(arrB[index]) ); }
// avoid division by zero (0) at this time -- causes errors -- add checks
function divArrays(arrB, arrA) { return arrA.map( (a, index) => Number(a) / Number(arrB[index]) ); }

//function sumem(elem) { console.log(calculateButtonArray(elem).join(',')); } // returned numbers
function sumem(elem) { console.log(calculateButtonArray(elem)); }         // for returned strings

function init() {
  var btns = document.querySelectorAll('#btnTable button');
  btns.forEach( function (elem) { elem.addEventListener( 'click', function () { sumem(elem) } ) } );
} init();

</script>
</body></html>

I’m sorry but it seems that you still misunderstand the nature of the project.
His test page might help you to understand things more clearly.
http://www.reedyrace.com/ae/runtime/testing-buttons.html

I reread all the posts of this thread and the example link (standing alone) does not help.
Two keyboards of 25 keys in various directions (up, down, in, out, right, left) without further explaination is like an icon with little meaning other than to look nice. Without instructions as to what conditions to choose which button, the results do not make intuitive sense. To me it would need an instruction manual or some hands-on OJT to know what to do with those buttons. Or maybe you need an engineering degree to use it.

If the problem is to take the value of a button (comma separated values) and add it to the value of a second button, then I think I understand. The wording of the original request was unclear to me. If there a different way to interpret the OPs original request that I continue to miss? I would be glad to be enlightened.

My code suggestion was not intended to be the final output for the OP as they seem to have the design layout to their liking. That is fine. My code differs in that a running total of all buttons pressed (added, subtracted, added and divided) is displayed. Obviously that could be changed with the button settings and actions when buttons are pressed. along with different CSS settings.

My suggestion removed the need for IDs to each button (one of the OP’s original requests) as well as providing a common function to add the button values (after removing the other mathematical functions). As with any other suggestion (code or otherwise), the OP is welcome to approve or reject or ignore the suggestions. I’ll leave making the display compatible to the OP’s needs with CSS to them. I think I now understand the problem with 4 values for each button to produce a sum for two buttons (either having the same or different values) which was initially unclear to me and was not cleared with the subsequent button keypad displays (links).

I feel I gained some understanding from the posting of 'fengxh’s function. It may not help the OP, but it did help me. In fact, I could see how the underlying setup and solution(s) could be applied to other problems like
a. matrix calculations and display or
b. other summation displays (like: cost, quantity, subtotal, discount, total) or
c. educational tables interactions (add, sub, mult, div, power, exponents, etc).
d. other projects where multiple functions could be accomplished with a single button.

I look forward to continued learning from this forum site in other threads of topics (HTML, JS, CSS, etc.) and I appreciate your insightful analysis. If I have misunderstood the nature of the project with my suggestions, I apologize. I still continue to learn (hopefully)!

Clicking on one button in the first tab (with 4 values) and clicking on 1 button in the second tab (with 4 values), they are added together and the sum put in the boxes in the third tab.

toe = tab1[0] + tab2[0] + 3
antisquat = tab1[1] + tab2[1] + 1

… and so on for [2] and [3].

I’m confused as to why the sums code is broken. I added code to display the corresponding selection with a graphic, but now the figures don’t add up in the Results tab. I carefully named the variables so they don’t halt the sums, so I don’t see why there would be an interruption. No errors in the Console.

<script>
const zeroValues = [0,0,0,0];
let cMount = zeroValues;
let dMount = zeroValues;
function getValues(buttonValue) {
    if (buttonValue.split(",").length > 4) { //was 5 when 5 values / 4
        return buttonValue.split(",").slice(0, 4); //was (1, 5) when 5 values / (0,4)
    }
    return zeroValues;
}

function assignValues(button) {
    const values = getValues(button.value);
    if (button.parentNode.classList.contains("grid-divc")) {
        var cMount = values;
			document.getElementById("cMountLeft").innerHTML = ""; /* clear the value in this tab */
			document.getElementById("cResultsLeft").innerHTML = ""; /* clear the value in this tab */
			document.getElementById('cInsertChosen').innerHTML = cMount; /* display the values in this tab */
			document.getElementById("cResultstoe").innerHTML = cMount[0]; /* display the value across the 4 grid cells... */
			document.getElementById("cResultsantisquat").innerHTML = cMount[1]; 
			document.getElementById("cResultspWidth").innerHTML = cMount[2]
			document.getElementById("cResultspHeight").innerHTML = cMount[3]; 
			c_Mount = cMount[0] + "," + cMount[1] + "," + cMount[2] + "," + cMount[3]; /* format the output with commas */
		switch (c_Mount) {  /* Add image of C setup selected. This works */
			case "-1,1,0.7,0.7":
				var leftImg  = "c-mount_1-corner.png";
				document.getElementById("cMountLeft").innerHTML = "<img src='images/" + leftImg + "' class='cMountLeftImg'>";
				document.getElementById("cResultsLeft").innerHTML = "<img src='images/" + leftImg + "' class='cMountLeftImg'>";
				break;
			case "1,1,0.7,0.7":
				var leftImg  = "c-mount_1-corner.png";
				document.getElementById("cMountLeft").innerHTML = "<img src='images/" + leftImg + "' class='cMountLeftImg'>";
				document.getElementById("cResultsLeft").innerHTML = "<img src='images/" + leftImg + "' class='cMountLeftImg'>";
				break;
			}
    }
    if (button.parentNode.classList.contains("grid-divd")) {
        dMount = values;
			document.getElementById("dMountLeft").innerHTML = "";
			document.getElementById("dResultsLeft").innerHTML = "";
			document.getElementById('dInsertChosen').innerHTML = dMount;
			document.getElementById("dResultstoe").innerHTML = dMount[0];
			document.getElementById("dResultsantisquat").innerHTML = dMount[1]; 
			document.getElementById("dResultspWidth").innerHTML = dMount[2];
			document.getElementById("dResultspHeight").innerHTML = dMount[3]; 
			d_Mount = dMount[0] + "," + dMount[1] + "," + dMount[2] + "," + dMount[3]; 
		switch (d_Mount) { 
			case "-1,1,0.7,0.7":
				var leftImg  = "d-mount_1-corner.png";
				document.getElementById("dMountLeft").innerHTML = "<img src='images/" + leftImg + "' class='dMountLeftImg'>";
				document.getElementById("dResultsLeft").innerHTML = "<img src='images/" + leftImg + "' class='dMountLeftImg'>";
				break;
			case "1,1,0.7,0.7":
				var leftImg  = "d-mount_1-corner.png";
				document.getElementById("dMountLeft").innerHTML = "<img src='images/" + leftImg + "' class='dMountLeftImg'>";
				document.getElementById("dResultsLeft").innerHTML = "<img src='images/" + leftImg + "' class='dMountLeftImg'>";
				break;
			}
    }
}
function addButtons(cMount, dMount) {
    const added = cMount.map(function addTogether(value, index) {
        return Number(value) + Number(dMount[index]);
    }); 
	alert("cMount = " + cMount); /* returns 0,0,0,0 */
    return added;
	alert("cdMount = " + dMount); /* returns 0,0,0,0 */
}
function updateResults(added) { 
    document.querySelector("#toe").innerHTML = Math.round(added[0]*100)/100 + 3;
    document.querySelector("#antisquat").innerHTML = Math.round(added[1]*100)/100 + 1;
    document.querySelector("#pWidth").innerHTML = Math.round(added[2]*100)/100;
    document.querySelector("#pHeight").innerHTML = Math.round(added[3]*100)/100;
	alert("(added[0] = " + added[0]); /* returns 0,0,0,0 for C (s/b -1). Then returns correct for D (-1). So the C is not being captured and added to D. */
}
function processButton(button) {
    assignValues(button);
    const added = addButtons(cMount, dMount);
    updateResults(added);
}
function buttonClickHandler(evt) {
    evt.preventDefault();
    let el = evt.target;
    while (el && el.nodeName !== "BUTTON") {
        el = el.parentNode;
    }
    processButton(el);
}
var buttons = document.querySelectorAll(".grid-container button");
buttons.forEach(function (button) {
     button.addEventListener("click", buttonClickHandler, false);
});
</script>

Because much of the code relies on HTML content before it works or can be tested, there’s not much we can do to help until a test page involving both the HTML and the JavaScript is put together.

Understood. I think I’ll first start removing parts of those lines to all of them to see what effect they have. If I delete them all and it works, I’ll add them back in sparingly and see where it breaks.

Here’s the problem: I had added “var” here. Can you tell me why that’s a problem? Isn’t it a var?

It is now working successfully. The numbers are adding together again. I had compared your code and mine carefully and found the discrepancy.

The earlier variables for cMount and dMount are defined so that they can be changed and updated.

let cMount = zeroValues;
let dMount = zeroValues;

When you used var cMount in the function, you created a new and unrelated cMount variable inside that function, the clobbered that original variable further up.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.