How to make an input have more than one event?

Viewed 398

I have a button and a select in my form. The button has onclick event while the select has onchange event. How to make the select has both onclick and onchange event?

This is the script:

$('#i_btn').on('click', function(){
     alert('Event 1');
});

$('#i_sel').on('change', function(){
     alert('Event 2');
});

When the select is changed, it should do alert('Event 1'); alert('Event 2');. I do not want to rewrite the onclick code in onchange

4 Answers

Write your events as separate functions :

$('#i_btn').on('click', event1);
$('#i_sel')
     .on('change', event1)
     .on('change', event2);

function event1(){
     alert('Event 1');
}

function event2(){
     alert('Event 2');
}

You can trigger the click event of #i_btn in the change event of #i_sel

$('#i_btn').on('click', function(){
     alert('Event 1');
});

$('#i_sel').on('change', function(){
     alert('Event 2');
     $("#i_btn").trigger("click");
});

You can use trigger inside the on change of the select make sure you have defined buttons on click before on change

$('#btn1').on('click', function(){
     alert('Clicked');
});

$('#select1').on('change', function(){
     alert('Changed');
     $("#btn1").trigger("click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<select id="select1">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
<button id="btn1">click</button>

You could also simply add the event handler to the element...

$('#i_btn, #i_sel').on('click', function(){
     alert('Event 1');
});

$('#i_sel').on('change', function(){
     alert('Event 2');
});

Unless you really need the click to trigger on the button...

Related