0

I have an eventlistener for an html element X that will hide some other elements whenever X's value changes.

I have another function that will change X's value. However when this function executes and changes X's value the eventlistener change doesnt trigger.

In this case X is "sa_placement_type". And this elements value is changed with the first event listener below.

document.getElementById("form_1").addEventListener("change", function(e) {
    var changed_id = e.target.id,
        changed_type = e.target.type,
        changed_value = e.target.value,
        target_id,
        target_ele;

    if (changed_id.endsWith("_preview")) {
        target_id = changed_id.substring(0, changed_id.length - 8),
        target_ele = document.getElementById(target_id);

        /*This is where the elements value is changed, should trigger event listener below.*/
        target_ele.value = changed_value;
    }

});

document.getElementById("sa_placement_type").addEventListener("change", function () {
    var sa_type = document.getElementById("sa_placement_type"),
        wrapper_percent = document.getElementById("div_placement_percent"),
        wrapper_flatfee = document.getElementById("div_placement_flatfee");

    if (sa_type.value == 'PercentageFee') {
        wrapper_percent.style.display = 'block';
        wrapper_flatfee.style.display = 'none';
    } else if (sa_type.value == 'FlatFee') {
        wrapper_percent.style.display = 'none';
         wrapper_flatfee.style.display = 'block';
    }
});
jjyj
  • 377
  • 4
  • 15
  • Can you add the HTML and make this an executable [Stack Snippet](https://stackoverflow.blog/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) – Barmar Jun 30 '17 at 21:22
  • The `change` event only occurs when the value is changed by the user, not when it's changed by Javascript. – Barmar Jun 30 '17 at 21:24
  • Yeah I created a function to manually just call and update on that element. So it works, but I kind of feel dirty because I'll probably have to add more manual functions for similar cases....Is there any other alternative way to detect variable changes via JS? – jjyj Jun 30 '17 at 21:35
  • 1
    See https://stackoverflow.com/questions/2490825/how-to-trigger-event-in-javascript – Barmar Jun 30 '17 at 21:37

0 Answers0