Reputation: 8723
How can I listen to the onChange
Event of multiple jQuery objects?
var el1= jQuery('input[type="checkbox"][name="x"]');
var el2= jQuery('input[type="checkbox"][name="y"]');
jQuery(el1, el2).change(function (e) {
//....
});
Of course I could just put the 2 element selectors as a string into the
.change
function, but this is a simplified example. I would like to work with the jQuery objects, not with string selectors.
This looked like a simple "let me google for you" question to me, but I have not been able to find a solution for the past hour.
Upvotes: 1
Views: 55
Reputation: 2127
You can use .add()
:
el1.add(el2).on('change', function () { /* body */ });
Upvotes: 1
Reputation: 25371
You can use add()
or merge()
method:
Add:
el1.add(el2).change(function (e) {
//....
});
Merge:
$.merge(el1, el2).change(function (e) {
//....
});
Upvotes: 1
Reputation: 5488
Try this
var el1 = jQuery('input[type="checkbox"][name="x"]');
var el2 = jQuery('input[type="checkbox"][name="y"]');
$(document).on('change', [el1, el2], function() {
console.log('multiple')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="el1">Element 1</label>
<input id="el1" type="checkbox" name="x" value="test1" />
<label for="el2">Element 2</label>
<input id="el2" type="checkbox" name="y" value="test2" />
Also it is the first result of google and the main link is this
Upvotes: 1