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.
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.
document. querySelector('#test'). addEventListener('change', () => console.
the expected should be onchange event has to be call both the functions. You can only assign a handler to onChange once.
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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With