Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to expand an onchange event with JavaScript

This is a question I ran into about expanding on an element's JavaScript onchange event. I have several select elements that conditionally will have one onchange event attached to each of them (when they change to specific values, it hides/unhides certain elements). I want to conditionally add or append to another onchange event so they set a global variable if they do change without modifying or disabling the previous function already attached to them. Is there a way to "append" an additional function or add more functionality onto the already existing one?

Here is what I believe an example would be like:

<select id="selectbox1">
    <option>...</option>
    <option>...</option>
</select>

if (<certain conditions>) {
    document.getElementById("selectbox1").onchange = function () { 
        //hides elements to reduce clutter on a web form ...
    }
}
....
if (<other conditions>) {
    document.getElementById("selectbox1").onchange = function2 () {
        //set global variable to false
    }
}

Alternatively I'd like to simply add the 1-liner "set global variable to false" to the original function.

like image 373
Brian Avatar asked Jun 03 '09 18:06

Brian


People also ask

How do you write Onchange in Javascript?

The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.

How can I trigger an Onchange event manually in Javascript?

document. querySelector('#test'). addEventListener('change', () => console.

Can we use two Onchange event in Javascript?

the expected should be onchange event has to be call both the functions. You can only assign a handler to onChange once.


1 Answers

You can cheat by simply having a composite function that calls the other functions.

document.getElementById("selectbox1").onchange = function() {
    function1();
    function2();
}

You can also use the observer pattern, described in the book Pro JavaScript Design Patterns. I have an example of its use in an article (here).

//– publisher class — 
function Publisher() { 
    this.subscribers = []; 
};

Publisher.prototype.deliver = function(data) { 
    this.subscribers.forEach(function(fn) { fn(data); }); 
};

//– subscribe method to all existing objects 
Function.prototype.subscribe = function(publisher) { 
    var that = this; 
    var alreadyExists = publisher.subscribers.some(function(el) { 
        if (el === that) { 
            return; 
        } 
    });

    if (!alreadyExists) { 
        publisher.subscribers.push(this); 
    } 
    return this; 
};
like image 71
Joel Martinez Avatar answered Oct 28 '22 19:10

Joel Martinez