Jorz
Jorz

Reputation: 358

Javascript: Run multiple functions using onChange

I have this Javascript/HTML snippet:

var select = document.getElementById("selectMe");
function loadMe()
{
    select.onchange = updateMe;
}

function updateMe()
{
    alert("I am updated");
}

function updateMeToo()
{
    alert("I am updated too!");
}

function updateMeAlso()
{
    alert("I am also updated!");
}
loadMe();
<select id="selectMe">
    <option>foo</option>
    <option>bar</option>
</select>

The above code works fine but

Question:

How can I run multiple functions on the code's "select.onchange" part?

I tried something like this:

select.onchange = updateMe; updateMeToo; updateMeAlso;

And as expected, it doesn't work. I want to stick with my code as possible. I also searched for some related issues but nothing helped.

Upvotes: 0

Views: 1692

Answers (3)

Sergiy Seletskyy
Sergiy Seletskyy

Reputation: 17110

You can use addEventListener to add as many functions as you want.

var select = document.getElementById("selectMe");

select.addEventListener("onchange", loadMe, false);
select.addEventListener("onchange", updateMe, false);
select.addEventListener("onchange", updateMeToo, false);
select.addEventListener("onchange", updateMeAlso, false);

The main benefit is that you can remove any of those functions (event listeners) at any time later in any sequence without impacting other listeners. Just make sure you use the same list of arguments as it was for adding listener.

select.removeEventListener("onchange", updateMeToo, false);

You can read more about that 'mystical' third argument (useCapture) here

Of course this pattern doesn't work with anonymous/arrow functions, because you need a name (a pointer) of the function to unregister it later. Here is an example which doesn't work

// you can add anonymous function
select.addEventListener(
  "onchange",
  function () { updateMe(), updateMeAlso(),updateMeAlso() },
  false
);

// but you cannot remove anonymous function from event listeners
select.removeEventListener(
  "onchange",
  function () { updateMe(), updateMeAlso(),updateMeAlso() },
  false
);

Upvotes: 2

Mairaj Ahmad
Mairaj Ahmad

Reputation: 14604

Try this

select.onchange = function () { updateMe(), updateMeAlso(),updateMeToo() };

Upvotes: 3

Abana Clara
Abana Clara

Reputation: 4650

select.setAttribute('onchange','updateMe(); updateMeToo(); updateMeAlso();');

is my usual practice, I know you already accepted an answer but this works just as fine.

Upvotes: 1

Related Questions