Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dispatchEvent change on select element cannot be handled by delegate

I have the following html snippet:-

        <fieldset id="container">
            <legend>Event Delegation Test</legend>
            <button type="button" id="btn_select" name="select button">Select</button>
            <input type="text" name="first" autofocus/>
            <input type="text" name="second"/>
            <input type="text" name="third"/>
            <input type="text" name="fourth"/>
            <input type="text" name="fifth"/>
            <select name="Names">
                <option>Tom</option>
                <option>Dick</option>
                <option>Harry</option>
            </select>
        </fieldset>

I have set event delegation on the fieldset (id="container") and added the change event thus:

document.getElementById("container").addEventListener("change", e => {
let el = e.target,
        name = el.name,
        value = el.value;

console.log("CHANGE element: %s has value %s", name, value);});

I have found that using the following code...

select.value = "Harry";
select.dispatchEvent(new Event("change"));

...isn't detected by the delegate handler.

BUT this does work...

select.value = "Harry";

let ce = new CustomEvent("change", {
    bubbles: true,
    cancelable: false
});

select.dispatchEvent(ce);

WHY?

I have been unable to find any information as to this particular use case peculiarity Any enlightenment would be greatly appreciated.

like image 679
reg1965 Avatar asked Mar 06 '23 17:03

reg1965


1 Answers

You have to explicitly specify that the event propagates:

new Event("change", {"bubbles": true});

The default value for the event propagation (propertie bubbles) is false. That is why your delegate handler is not receiving the change event.

like image 170
f-CJ Avatar answered Mar 09 '23 06:03

f-CJ