I am trying to get a dropdown selected value on change event. Unfortunately I did not get value selected. The following output result. If you click the dropdownlist again then it will get value correctly.
First Click Output
You clicked on a SPAN
The innerHTML is
The text is
The parentNode is DIV
On Second Click the output
You clicked on a SPAN
The innerHTML is <span>Active</span>
The text is Active
The parentNode is DIV
So basically it only capture on click not on change value. If I change this line of code the following does not seem to work either
From:element.addEventListener("click", function (evt)
To: element.addEventListener("change", function (evt)
Current code:
<script>
function GetdrpSelected(e, param) {
var txt='You clicked on a '+e.target.nodeName+'n';
txt+='The innerHTML is '+e.target.innerHTML+'n';
txt+='The text is '+e.target.textContent+'n';
txt+='The parentNode is '+e.target.parentNode.nodeName+'n';
console.log(txt);
}
function attachEventListener(node) {
const element = node;
element.addEventListener("click", function (evt){
const elemId = node.childNodes[0].childNodes[0].id;
GetdrpSelected.call(this, evt, elemId);
});
}
function initCat(){
let wrappers = document.getElementsByClassName("ard-FormField-wrapper");
for (let i = 0; i < wrappers.length; i++) {
let formLabel = wrappers[i].childNodes[0];
if(formLabel.innerHTML !== '' && formLabel.innerHTML.toLowerCase().indexOf('change cat') > -1){
attachEventListener(wrappers[i].childNodes[1]);
}
}
}
const ddlCat = setTimeout(initCat, 2000);
</script>
6
your event listener is set to trigger on a click event rather than a change event
Instead of using e.target.nodeName
you can use e.target.value
like this :
function GetdrpSelected(e) {
let selectedValue = e.target.value;
console.log("Selected value:", selectedValue);
}
function attachEventListener(node) {
const element = node;
const dropdown = element.querySelector("select"); // Assuming your dropdown is a <select> element
dropdown.addEventListener("change", function (evt) {
GetdrpSelected(evt);
});
}
function initCat() {
let wrappers = document.getElementsByClassName("ard-FormField-wrapper");
for (let i = 0; i < wrappers.length; i++) {
let formLabel = wrappers[i].childNodes[0];
if (
formLabel.innerHTML !== "" &&
formLabel.innerHTML.toLowerCase().indexOf("change cat") > -1
) {
attachEventListener(wrappers[i].childNodes[1]);
}
}
}
const ddlCat = setTimeout(initCat, 2000);
3