datalist: dispatch a custom event when the selection changed - jscancer - Javascript crap (relatively small)
 (HTM) git clone git://git.codemadness.org/jscancer
 (DIR) Log
 (DIR) Files
 (DIR) Refs
 (DIR) README
 (DIR) LICENSE
       ---
 (DIR) commit b37e29b608c9df10ba3e50ebeeb1fd4365323318
 (DIR) parent aa6690aad0a7b64010561df965d589b8f1a59a75
 (HTM) Author: Hiltjo Posthuma <hiltjo@codemadness.org>
       Date:   Mon, 25 Mar 2024 20:47:59 +0100
       
       datalist: dispatch a custom event when the selection changed
       
       Can be useful for some custom callback.
       
       Diffstat:
         M datalist/datalist.js                |      12 ++++++++++--
       
       1 file changed, 10 insertions(+), 2 deletions(-)
       ---
 (DIR) diff --git a/datalist/datalist.js b/datalist/datalist.js
       @@ -27,6 +27,13 @@ function datalist_init(input) {
                        return el.textContent || el.innerText || "";
                };
        
       +        var setvalue = function(el, value) {
       +                if (el.value !== value) {
       +                        el.value = value;
       +                        el.dispatchEvent(new Event("selection-changed"));
       +                }
       +        };
       +
                // create item: expects string, or object with name and label attribute.
                var createitem = function(o) {
                        var label, value, div = document.createElement("div");
       @@ -45,7 +52,7 @@ function datalist_init(input) {
                        div.innerHTML = label;
                        div.setAttribute("data-value", value);
                        div.addEventListener("mousedown", function() {
       -                        input.value = getvalue(this);
       +                        setvalue(input, getvalue(this));
                                datalist_show(false);
                        }, false);
                        div.addEventListener("mousemove", function() {
       @@ -174,12 +181,13 @@ function datalist_init(input) {
                        if (el)
                                el.className = "sel";
                };
       +
                input.addEventListener("keydown", function(e) {
                        mouse = false;
                        switch (e.which) {
                        case 13: // return
                                if (cursel)
       -                                input.value = getvalue(cursel);
       +                                setvalue(input, getvalue(cursel));
                                if (!datalist_visible)
                                        return;
                                datalist_show(false);