0

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.

0

3 Answers 3

3

Try this

select.onchange = function () { updateMe(), updateMeAlso(),updateMeToo() };
Sign up to request clarification or add additional context in comments.

Comments

2

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
);

Comments

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

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

1 Comment

You can easily put parameters using setAttribute versus addEventListener

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.