Streaming live at 10am (PST)

Math using CMS fields

Hey Anthony, I guess my question was more about the actual syntax. I wouldn’t know where to begin.

Would it be in JS, CSS or HTML?
Maybe stack overflow is a better place for this kind of question

Well I guess you could use a simple vanilla Javascript snipet like so:

Javascript

// 🥑 on DOM loaded
document.addEventListener("DOMContentLoaded", event => {
  const element = document.getElementById("element");
  // getting the values of prep and cook time
  let prep = Number(document.getElementById("prep").value),
    cook = Number(document.getElementById("cook").value);

  const sum = (a, b) => a + b,
    result = sum(prep, cook);

  element.innerHTML = `${result} minutes`;
}); // end DOM listener

Webflow HTML embed:

<!--need to replace the values by whatever {{your cms field name}} are-->
<input type="hidden" id="prep" value="20">
<input type="hidden" id="cook" value="10">
<span id="element"><span>

Where instead of the actual integer values I used for example, you’d use the CMS field from Webflow I talked to you earlier.

Here is a quick codepen for you.

3 Likes

Thanks for this! I’ve since started a JS course and this is extremely helpful.
I love the addition of the little food emojis in the code btw :joy:

1 Like

How would you add up multiple numbers e.g. 10!

I’ve tried to adjust the code and it’s not returning anything…

Screen Shot 2020-07-23 at 12.59.55 PM

How do you do this with more than 2 values?

For more than two numbers, I would suggest another approach. I would create an empty array, then run a function that would get all inputs by class name, get their respective values and store those values into that empty array. Once we have all values stored, we can start working with them and make good use of the modern ES6 reduce method especially designed for array manipulation.

Codepen update: here

JavaScript:

// 🥦 when the DOM has loaded
document.addEventListener("DOMContentLoaded", () => {
  // set globals
  const inputs = document.getElementsByClassName("input"),
    result = document.getElementById("result");
  let value,
    values = [],
    sum;

  // 🧄 for each input of the array
  Array.from(inputs).forEach((input) => {
    // get value of each input by explicit coercion
    value = Number(input.value);
    //inject each value into empty "values" array
    values.push(value);
  });

  // 🥕 run a reduce function on the array
  sum = values.reduce((a, b) => {
    // return the sum of the accumulator (a) + its current value (b)
    // in other words: 0(a) + 1(b) = 1 | 1(a) + 2(b) = 3 | 3(a) + 3(b) = 6
    return a + b;
  }, 0); // default accumulator's value starts with 0

  // 🥗 inject result into the DOM + plural management
  result.textContent = `${sum} minute${sum > 1 ? "s" : ""}`;
}); // end DOM loaded

HTML

<span>🥦 + </span><input class="input" type="hidden" value="1">
<span>🧄 + </span><input class="input" type="hidden" value="2">
<span>🥕 + </span><input class="input" type="hidden" value="3">
<!-- add as many input as you want... -->
<span>🥗 = </span><span id="result"><span>

Expected output:

:broccoli: + :garlic: + :carrot: + :green_salad: = 6 minutes

Not sure about the quality of that salad thoug :upside_down_face:
I hope that helps.

2 Likes

Wow!!

Thank you so much this worked PERFECTLY.

1 Like

This is opening op doors!!
So i have a variable number in about 400 collection items.
I need to show the sum of these values.
How could i do that?

well all of your collection items need to be present on the page, only then can the values be targeted to return the sum

Well that is possible, since i already check out all items in an embedden Google Maps system.
So i already have 400 items on one page.

Now i need to get all their kWh numbers and add these up to show the total!
Any idea’s/examples/tips?

would you have a read only or a published page for us to have a look at ?

1 Like

Ofcourse! https://preview.webflow.com/preview/agro-nrg?utm_medium=preview_link&utm_source=designer&utm_content=agro-nrg&preview=3cfb6dd66314c002bcb269da2e72239a&pageId=5e283aeb321c3d42a4c5b266&mode=preview

Is about the total power “totaal wattage” and total panels “Totaal aantal panelen”.
These are all in the 3 “map_collection” lists.
(these are hidden atm, because they feed the Google Maps Canvas with the proper locations)

The live page is on: https://agro-nrg.webflow.io/agro-projecten

Do you mean all the numbers inside the project-wp xm combo class div ?

The list of project-wp xm only show the last/newest and only consist of 100 items.
Ideally you’d want to get the kWp of 3 hidden collection lists used for Google Maps.

They generate a script, and the ‘name’ there represents the kWp.
you’d want map_collection w-dynlist w-dyn-items w-dyn-item w-embed w-script and then the cars.push ‘name’.

And then add up all the dyn-items from all 3 map_collection w-dyn-list's

We could use another approach instead of trying to get the name key/value pairs for each CMS items contained in the javascript object, we could simply query what your initial empty cars array contains once the DOM has finished loading and all the values have been populated or pushed into the cars array.

Here is a quick codepen for you

You could rewrite the script where you have your empty array like so:

Javascript

document.addEventListener("DOMContentLoaded", () => {
  const log = console.log,
    cars = [], // initial empty array
    values = [];

  // simulate CMS data being pushed
  // 🍋 remove this car.push() function for production
  cars.push(
    { name: 1, xyz: "abc" },
    { name: 2, xyz: "def" }
  );

  Array.from(cars).forEach((item) => {
    values.push(item.name);
  });

  const target = document.getElementById("target"),
    sum = values.reduce((a, b) => Number(a) + Number(b), 0);
  target.textContent = sum;
  log(values);
});

and then in your webflow layout setup a span with an id of target into which the javascript will inject the sum of the cars array.

HTML

<p>total: <span id="target"></span></p>

Some screenshots from which I based my idea from:

Hope that helps.

1 Like

You are most kind!
I will try this first thing tomorrow!
Fingers crossed!

PS. thx for the lemon!!

I tried pasting your code (without the demo pushes) before </body> and added the custom code with the target span. I do get a value, but unfortunately, it’s 0 :slight_smile:.

image

image

Something i did wrong? or should i put the script somewhere else?

I’ve tried it in multiple locations for the script (before end body, in head), including in the already present script where the var cars = []; is and put it below there. Still it returns 0.

PS. If i change the starting value (0) to something else, it does show. So the basics seem to work.

Update:
Could it be that the way the values are pushed with the ’ ’ signs, that it doens’t pick those up correctly? This is how the script looks for one item:

image

PS. you can check my findings in same preview link or here: https://agro-nrg.webflow.io/agro-projecten (down below the map)

side question: Can you also put the sum with punctuation? so 1000 » 1.000 and 1000000 » 1.000.000 ?

You need to replace the cars = [] of your old code snipet by the new one, there shouldn’t be two times cars = [] in your code. As for the <p>total: <span id="target"></span></p> you can simly inject it into a webflow custom code embed component within your layout. The '...' or quotes wrapping your numbers in your javascript have no effect because in the script I wrote, I wrapped the a and b values within the Number() method which coherce strings into numbers. If the quotes would have been an issue, you’d see a NaN (Not a Number) value into your target span. As for your formating question, sure it’s possible to format the numbers with punctuation, that is one or two javascript lines.

1 Like