0

I need to convert following jquery script into javascript

<script type="text/javascript">

  window.addEventListener("load", function() {
    jQuery(function($) {
      $('select.ddlVarianti').on('change', function() {
        var optionSelected = $(this).find("option:selected");
        var tagliaSelected   = optionSelected.text();
        window.dataLayer = window.dataLayer || [];
        dataLayer.push({
          'event':'GAevent',
          'eventID':'13',
          'eventCategory':'product',
          'eventAction':'taglia',
          'eventLabel': tagliaSelected,
        });

      });
    });
  });
</script>

This is what i did

  document.querySelector('select.ddlVarianti').addEventListener('change', function() {
    var optionSelected = document.querySelector(this).querySelector("option:selected");
    var tagliaSelected   = optionSelected.text();
    window.dataLayer = window.dataLayer || [];
    dataLayer.push({
      'event':'GAevent',
      'eventID':'13',
      'eventCategory':'product',
      'eventAction':'taglia',
      'eventLabel': tagliaSelected,
    });

  });

but i have following error..

Failed to execute 'querySelector' on 'Document': '[object HTMLSelectElement]' is not a valid selector.

Thanks for any suggestion

3
  • Please show the HTML related to this. In particular, is there one select.ddlVarianti element, or more than one? Commented Oct 1, 2022 at 10:21
  • 2
    document.querySelector(this) is the code causing the problem. You can't pass an element object into querySelector. Commented Oct 1, 2022 at 10:21
  • For starters change this 'change', function() to this 'change', function({ target }). Then change this document.querySelector(this).querySelector("option:selected"); to this target.querySelector("option:checked"); Commented Oct 1, 2022 at 11:49

1 Answer 1

1

There are three issues I can see (maybe only two):

  1. document.querySelector(this) is passing an element object into querySelector. You can't do that, it accepts strings defining CSS selectors. To look within the element this refers to, use this.querySelector("selector string"). But if you want to get the seelcted option from an HTMLSelectElement, you can use its selectedOptions array instead.

  2. option:selected is jQuery-specific. To find the first selected option within the select, you can use "option:checked" instead. But see #1, you don't need to do it that way.

  3. The jQuery code is waiting for the window load event and then, redundantly, waiting until the DOM is ready (which it will be; load doesn't fire until long after it is). Your code isn't doing anything to wait for things to be ready. These days, if you're using type="module", there's no need to, so that may be fine. If not, you might consider it (modules are useful), or use defer on the script element.

You haven't said whether there is just one element or multiple but if we assume multiple, loop through the result of querySelectorAll to set up the handlers:

for (const element of document.querySelectorAll("select.ddlVarianti")) {
    element.addEventListener("change", function () {
        const optionSelected = this.selectedOptions[0];
        if (optionSelected) {
            const tagliaSelected = optionSelected.text;
            window.dataLayer = window.dataLayer || [];
            dataLayer.push({
                event: "GAevent",
                eventID: "13",
                eventCategory: "product",
                eventAction: "taglia",
                eventLabel: tagliaSelected,
            });
        }
    });
}

Live Example:

for (const element of document.querySelectorAll("select.ddlVarianti")) {
    element.addEventListener("change", function () {
        const optionSelected = this.selectedOptions[0];
        if (optionSelected) {
            const tagliaSelected = optionSelected.text;
            console.log(`tagliaSelected = ${tagliaSelected}`);
            /*
            window.dataLayer = window.dataLayer || [];
            dataLayer.push({
                event: "GAevent",
                eventID: "13",
                eventCategory: "product",
                eventAction: "taglia",
                eventLabel: tagliaSelected,
            });
            */
        }
    });
}
<div>
    <select class="ddlVarianti">
        <option value="A">Option A</option>
        <option value="B">Option B</option>
        <option value="C">Option C</option>
        <option value="D">Option D</option>
    </select>
</div>
<div>
    <select class="ddlVarianti">
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
        <option value="3">Option 3</option>
        <option value="4">Option 4</option>
    </select>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.