Event Listener: The code begins by waiting for the DOM to be fully loaded. This ensures that the script doesn’t run until the web page is ready for interaction.
DOM Elements: It then selects three important elements:
selectElement: The dropdown or select element that allows users to choose product options.
addToCartButton: The button that adds the product to the cart.
priceItem: The element that displays the product price.
Disable Add to Cart: The
disableAddToCartfunction is defined to disable the “Add to Cart” button and hide the price initially. It achieves this by setting the
disabledproperty of the button to
trueand adding a CSS class
Create “Select an option”: It creates a new
<option>element with the value and text set to “Select an option.” This option serves as the default selection in the dropdown.
Insert Default Option: The script inserts the “Select an option” option at the beginning of the select element’s options list.
Set Initial Value: It sets the value of the select element to “Select an option” to make it the default selection.
Handle Select Change: The
handleSelectChangefunction is defined to handle changes in the select element. If a real option (not “Select an option”) is chosen, it enables the “Add to Cart” button and removes the
visually-hiddenclass from the price item, making the price visible. If “Select an option” is chosen, it calls the
disableAddToCartfunction to disable the button and hide the price again.
Event Listener: An event listener is added to the select element to listen for changes, and it triggers the
handleSelectChangefunction when a change occurs.
Initial Trigger: Finally, the
handleSelectChangefunction is called initially to simulate selecting “Select an option” when the page loads.