A store that sells popsicles

Let's start with a context, as a context makes the whole process fun. You want to sell frozen sweets. Each frozen sweet has its variants. Generally-speaking, these variants specify a quantity, and a flavor — and some sweets come with the option of being sugar-free. The following is a screenshot of the popsicle product page as it is now.

Your product page showing all variants without JavaScript

To be fair, there could be much more variants here. I was limited to 10 SKUs when I set up my fake shop for this tutorial. Still, seeing these 8 options in a table next to 8 radio buttons is not very pretty.

What we'd aim for would be something like this:

Your product page showing variants with JavaScript

The algorithm is super simple, and the JavaScript code needed to implement it will be easy too — easy enough.

  1. Hide the current selection box. (I say hide, not remove.)
  2. To the page, add select boxes and their labels based on reading the titles of all variants.
  3. Add a placeholder element to the page where we will display the price for the current selection.
  4. Add a listener to the new select elements so that whenever a visitor picks something from either of these boxes, we update the price displayed on the page and select the corresponding variant in the hidden select box. That hidden box will still be part of the document and its value will get submitted with the form when the customer clicks on the Add to Cart button.

That's it and all. Now, let's get to it.