Math using CMS fields

Hello there,

I am creating a “Recipe” page using the CMS. I would like to do some very basic math and display the result as a value on the CMS item page.

My collection items have:

  • Prep time
  • Cook time

I would like to then add those two variables and display a “Total time” field.
I know I can just use a custom embed and add the two fields within it.
I guess my issue is that I don’t know the proper syntax to calculate the two and display the information on the page.

Any help is appreciated!

@peej,

simply use custom fields pulled from your CMS inside your custom code embed. Have a look at this article (how to use dynamic embeds ony our webflow site).

Hope that helps.

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.

4 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.

3 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! Webflow - Agro-NRG

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: Agrarische Projecten 🌞 Agro-NRG

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)