Search code examples
javascripthtmldropdownkeyboard-maestro

How to activate Cascading Dropdown auto-selection using pure javascript


I'm trying to select a dropdown item via an Execute Javascript macro inside Keyboard Maestro. The code works to select and validate the dropdown item, but in the page I use this with, there are other dropdowns that should auto-populate based on the selection. When I click a dropdown item manually, the other dropdowns update accordingly. Via the javascript I'm using, it selects the item but leaves the other dropdowns. I need to use pure javascript and not jquery. Does anyone have any ideas on how to get the page to react based on the javascript selection?

// variable to enter into dropdown
var vDropdownInput = (document.kmvar.vZEROInput);

// variable to get the Element by ID
var objSelect = document.getElementById("web-selection_"+document.kmvar.vZEROIndex+"_");

// function to do the work
setSelectedValue(objSelect, vDropdownInput);


// function definition
function setSelectedValue(object, value) {
    for (var i = 0; i < object.options.length; i++) {
        if (object.options[i].text === value) {
            object.options[i].selectedIndex = i;
            return;

    }
}
    // Throw exception if option `value` not found.
    var tag = object.nodeName;
    var str = value;
    return str;
}

edit: I found this related post but I just don't get the proposed solutions. Select item in CascadingDropDown via JavaScript & invoke update


Solution

  • How do I programmatically force an onchange event on an input?

    This answered my question.

    var element = document.getElementById('just_an_example');
    var event = new Event('change');
    element.dispatchEvent(event);