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
CodePudding user response:
There are three issues I can see (maybe only two):
document.querySelector(this)
is passing an element object intoquerySelector
. You can't do that, it accepts strings defining CSS selectors. To look within the elementthis
refers to, usethis.querySelector("selector string")
. But if you want to get the seelcted option from anHTMLSelectElement
, you can use itsselectedOptions
array instead.option:selected
is jQuery-specific. To find the first selectedoption
within theselect
, you can use"option:checked"
instead. But see #1, you don't need to do it that way.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 usingtype="module"
, there's no need to, so that may be fine. If not, you might consider it (modules are useful), or usedefer
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 >
<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 >
<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>
CodePudding user response:
Something like this
document.querySelector('.select').addEventListener('change', (e) => {
const label = e.target.selectedOptions[0].innerText // selected label
const value = e.target.value // selected value
// Just to show selected value
document.querySelector('#selected-value').innerText = value
document.querySelector('#selected-name').innerText = label
// other code...
})
<div id="selected-value"></div>
<div id="selected-name"></div>
<select name="select" >
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>