Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind a jquery event to an array of jquery objects

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); 
});
like image 541
AndeeC Avatar asked Sep 28 '15 18:09

AndeeC


2 Answers

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

like image 86
charlietfl Avatar answered Sep 21 '22 00:09

charlietfl


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>
like image 29
Jpsy Avatar answered Sep 23 '22 00:09

Jpsy