Search code examples
javascriptjqueryhtmlacl

JQuery onChange uses values before change (values after change needed)


I am working on a module, which should select the only possible value of a Multi- or Single selection field, if there is only one valid value and a empty one available.

So far its working fine, until I use ACLs to disable selection values. For example, I got a single selection field with 3 possible values. Then I disable 2 of them (ACL - if there is a special Queue selected) so theres only one value (+ an empty one) left. My module wont pick the last value at first, but when I change anything else on the same page (second onchange call) it will pick the last possible value.

The first if condition checks if the Field has only one possible value in it. When I log the 'Change' array it always got the disbaled values still in there even when the 'change' that called the whole function was the ACL disabling those values.

Im still kinda new to javascript and havent found a solution yet.

I would realy appreciate any help.

$('.TableLike').on("change", function () {
        var Change = [];
        $('.Row').each( function() {
            $(this).children().next().children().next().children().each( function(index) {
                Change[index] = $(this).text()
            } )
            if ( (!Change[2] || /.*Field needed.*/i.test(Change[2])) && Change[0] === "-") {
                SoleOption = Change[1];
                $(this).children().next().children().next().children().each(function() {
                    if ($(this).text() === "-") {
                        $(this).removeAttr("selected");
                    }
                    if ($(this).text() === SoleOption) {
                        $(this).attr("selected", "selected");
                    }
                } )
                $(this).children().next().children().children().children().val(SoleOption)

            }
            SoleOption = "";
            Change = [];
        } )
    } )

Solution

  • I managed to fix the issue with the setTimeout() Method. So the DOM updated before the ACL did the changes. I opened up the setTimeout Method after the onChange method and inserted all the code thats supposed to run after the change into the setTimeout method.

    I hope this will be helpfull for others in the future.