0

I have not found any answer. So asking.

My HTML code

<button id="myButton">Click Me</button>
<select id="mySelect">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

My JS

$("#myButton").on("click", function(){
    alert("Hi");
});
$("#mySelect").on("change", function(){
    alert("Hi");
});

So in both events my function do the same thing. How can I combine these two events and type my function there? Is it possible?

I heard about trigger. I can use that. But want to know if there is any way to merge these events.

JSFiddle Demo

1
  • use a referenced function for that Commented Dec 23, 2013 at 12:41

2 Answers 2

6

Use one function, and reference it in the event handlers

$("#myButton").on("click", function_name);
$("#mySelect").on("change", function_name);


function function_name() {
    // code for both handlers goes here
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use javascript function

  <script>
    function clickme(){
    alert("Hi");
    }
    </script>    

<button id="myButton" onclick="clickme()">Click Me</button>
    <select id="mySelect" onchange="clickme()">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        <option value="4">4</option>
    </select>

Comments

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.