Need help setting a Cookie based on an element

I am not able to set a specific cookie based on a dropdown value. I have tried several times using a javascript. The script itself works and sets a default cookie, but i cant get my head around why the dropdown value is not working. No matter what, the Cookie value is just not reffering to the dropdown value. I dont get any errors in the browser, so there must be a problem with the connection to the dropdown.

Background: Via a dropdown my customers choose their delivery location. Based on the location I need to create a cookie, that my Shopify Page can pick up to than only show products available for this customers location.

I am an amateur in this field, so please dont destroy me with your knowledge :smile:

Here is the script I used. The Dropdown ID is “Brs_Dropdown_Orte”. The name of the Cookie “Packstelle”.

“function setPackstelleCookie(packstelleValue) “” const expires = new Date();” expires.setFullYear(expires.getFullYear() + 1);" console.log(“Setting packstelle cookie:”, packstelleValue);" document.cookie = packstelle=$"packstelleValue"; expires=$"expires.toUTCString()"; path=/;"""“function handleInput() “” const Brs_Dropdown_Orte = document.getElementById(‘Brs_Dropdown_Orte’);” console.log(“Input:”, Brs_Dropdown_Orte);" const selectedOrt = Brs_Dropdown_Orte.value;" console.log(“Selected Ort:”, selectedOrt);"" if (selectedOrt) “” console.log(“Setting the cookie with the selected value”);" setPackstelleCookie(selectedOrt);" " else “” console.log(“No selected value, keeping the default cookie”);" “”"""// Überprüfe, ob das Brs_Dropdown_Orte-Element vorhanden ist"// Wenn nicht, wiederhole den Vorgang alle 500 ms, bis es gefunden wird"function checkDropdownElement() “” const Brs_Dropdown_Orte = document.getElementById(‘Brs_Dropdown_Orte’);" if (Brs_Dropdown_Orte) “” Brs_Dropdown_Orte.addEventListener(‘input’, handleInput);"" // Setze einen Standardwert für den Cookie, nur wenn kein Wert im Dropdown ausgewählt ist" if (!Brs_Dropdown_Orte.value) “” setPackstelleCookie(“default”);" “” " else “” console.log(“Brs_Dropdown_Orte element not found, retrying in 500 ms”);" setTimeout(checkDropdownElement, 500);" “”"""// Beginne mit der Überprüfung, sobald die Seite geladen ist"document.addEventListener(‘DOMContentLoaded’, checkDropdownElement);"

Why dont you use Cookie Plugins?
It will be more easier than writing native js code.

1 Like