Articles on: Tutorials (how to)

Smart URL Parameters: Automating Element Selections with JavaScript

Introduction



In this article, we will explore how to automate the selection of checkboxes, radio buttons and dropdown menu items using JavaScript. This can be useful when you need to pre-select an option based on a URL parameter or other conditions. We will provide code examples and explain how to find the ID of the dropdown menu items.

## Finding the ID of The Checkbox or Dropdown Menu Items:

To find the ID of the dropdown menu items, you can use the developer tools in your web browser. Here's how:

Open the developer tools by pressing F12 or right-clicking on the dropdown menu and selecting "Inspect" or "Inspect Element".
In the developer tools, switch to the "Elements" tab.
Find the dropdown menu item you want to automate and click on it.
In the "Elements" tab, find the ID of the element in the "ID" attribute.

Code Examples



Dropdown Menu Javascript


Here is an example of how to automate the selection of a dropdown menu item using JavaScript. 
You can place this code anywhere on the page. Make sure you use your theme builders JS code module (or HTML code module).


<script>
setTimeout(() => {
  const sccDropdownParam = new URLSearchParams(window.location.search).get('dd');
  const sccCheckboxParam = new URLSearchParams(window.location.search).get('chk');

  if (sccDropdownParam) {
    // Simulate a click on the dropdown container to load the options
    const sccTsDropdownContainer = document.querySelector('.ts-control');
    sccTsDropdownContainer.click();

    setTimeout(() => {
      const sccTsDropdownOptions = document.querySelectorAll('[data-value]');
      sccTsDropdownOptions.forEach((sccTsDropdownOption) => {
        const sccTsDropdownValue = sccTsDropdownOption.dataset.value.trim();
        const sccDropdownParamTrimmed = sccDropdownParam.trim();
        if (sccTsDropdownValue !== null && sccTsDropdownValue === sccDropdownParamTrimmed) {
          sccTsDropdownOption.click();
        }
      });
    }, 50); // adjust the delay as needed
  }

  if (sccCheckboxParam) {
    // Simulate a click on the checkbox container to load the options
    const sccCheckboxContainers = document.querySelectorAll('.scc-form-field-item.df-scc-checkbox');
    sccCheckboxContainers.forEach((sccCheckboxContainer) => {
      const sccCheckboxInput = sccCheckboxContainer.querySelector(`input[id="itemcreated_0_0_0_0_${sccCheckboxParam}"]`);
      if (sccCheckboxInput) {
        sccCheckboxInput.checked = true;
      }
    });
  }
}, 1500);
</script>



URL Parameter Examples



Checkbox Example

https://stylishcostcalculator.com/templates/bakery-template/?chk=671

Dropdown Example

https://stylishcostcalculator.com/templates/bakery-template/?dd=666

Checkbox with Dropdown Example

https://stylishcostcalculator.com/templates/bakery-template/?dd=666&chk=671

Updated on: 21/06/2024

Was this article helpful?

Share your feedback

Cancel

Thank you!