I have an array containing jquery objects which are later referenced in various parts of the code. I put them into an array so that they are only selected once, rather than doing a jquery select every time I need to access them.
My question is, how can I bind a jquery event to an array of these jquery objects?
I used to do a jquery select on the IDs of the elements and then bind the event:
$('#name, #domain, #description').bind("blur change",
function () {
callEventHandler(this);
});
Now I have this array of jQuery objects. How can I bind these to a jquery event?
var jqObjs = [$('#name'), $('#domain'), $('#description')];
I tried doing this, but it didn't work:
$(jqObjs).bind("blur change",
function () {
callEventHandler(this);
});
Can loop over them:
$(jqObjs).each(function(_, jQobj){
jQobj.on("blur change",function () {
callEventHandler(this);
});
});
Since bind()
uses on()
internally I switched to use on()
instead.
An alternative would just store selectors
var jqSelectors = ['#name', '#domain', '#description'];
$(jqObjs.join()).on('...
I think it would help to understand how you even arrived at getting this array created. There are likely other approaches depending on use and what you are trying to accomplish
As explained in https://stackoverflow.com/a/44031991/430742 you can use jQuery's map()
to create a jQuery list object from your array. This object can then be used with .on()
to bind events to its elements.
var jqObjs = [$('#name'), $('#domain'), $('#description')];
var listObj = $.map(jqObjs, function(el){return el.get()});
$(listObj).on('click', function(ev){
console.log('EVENT TRIGGERED');
});
button{
display: block;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="name">Button 'name'</button>
<button id="domain">Button 'domain'</button>
<button id="description">Button 'description'</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With