Trick: setting default option for e-commerce variant

I have this problem too. The fix seems like it should work and is close to doing so but I still can’t get it working. If anybody can clarify the exact steps in a fool-proof manner, I’d be unbelievably grateful. (I’m trying to achieve the same as @matteogrand)

@Edward_Padmore and @matteogrand

DOMContentLoaded is not the page fully loaded and waiting. Therefore hooking the DOMContentLoaded results in subsequent “stuff” wiping out your javascript changes.

use the load event and it’ll fire after EVERYTHING is done with the page loading.

<script>
      window.onload = function () {

          (function select() {
          const selectButton = document.getElementsByClassName("select-field")[0];
          const defaultSelectedOption = selectButton.options[0];
          defaultSelectedOption.remove();
          const newDefaultSelectedOption = selectButton.options[0];
          newDefaultSelectedOption.selected = "selected";
       })()
   };
</script>

In my case I don’t like the default text to even show so I remove it and then set my selected item.

If this is confusing to anyone tag me and I’ll explain in a different thread.

3 Likes

OMG this worked! Thank you very much @patrickh - appreciate your help

1 Like

Hello !
Do you know if this solution could work to change the preselect variant for a product page with a variable.

Like this :
Customer A - Product 1 - Preselect Variant A
Customer B - Product 1 - Preselect Variant B

Hi @anthonysalamin is it possible to have one option as Buttons and the other would be the Select Dropdown (like you have here)?

I have a use case where one is for color and the other is for date.

@patrickh Thank you so much for taking the time to help out strangers on the internet. It is so very appreciated.

I feel like I’m nearly there but still having trouble. My result is that the new default selection is not visible (the text is hidden) and also that it appears to affect only the first field on the page is affected (there are two).

Any ideas?

https://neuhaus-test.webflow.io/product/hummingbird