t.c
t.c

Reputation: 1257

How can I add an event observer for each element I find on the page?

I'm working with Prototype on a script to detect all Select Tags under a Div and then add an event/observer on each one!

Here is the code to find the Elements I need:

Event.observe(window, 'load', function() {
  var tab=$("product-options-wrapper").descendants();
  var attCode=[];
  var j=0;

  for (i=0;i<tab.length;i++) {
    if (tab [i].tagName =="SELECT") {
      attCode[j++]=tab[i].id
    }
  }
});

I have all the Ids I need. How can I add an observer (on change) for each one?

$(id).on("change", function(event) {
  alert(id+"__"+$(id).value);
});

Upvotes: 1

Views: 840

Answers (3)

dontGoPlastic
dontGoPlastic

Reputation: 1782

Prototype supports event delegation out of the box. Event.on takes on optional second selector parameter. So in your case:

$("product-options-wrapper").on('click', 'select', function(event, element) {

  // This callback will only get fired if you've clicked on a select element that's a descendant of #product-options-wrapper
  // 'element' is the item that matched the second selector parameter, in our case, the select.

  ....

});

That parameter can be any CSS selector string:

$('my-element').on('click', '.some-class', function(event, element) { ... });

Check out Element.select, too. That will condense the code in your original question down to essentially one line:

$("product-options-wrapper").select('select');

This one seems kind of confusing because your selector string is 'select' (you want all SELECT elements under #product-options-wrapper). You could also do:

$$('#product-options-wrapper select');

These both return an array of matched elements.

HTH

Upvotes: 3

Marc
Marc

Reputation: 6771

That should do. Please post your html or even better a jsfiddle if you need more help.

$(function(){
    $('#product-options-wrapper select').on("change", function(e) {
       alert(id+"__"+$(this).val());
    });
});

I guess you forgot the . at the beginning of product-options-wrapper to indicate its a class? Or is it really a tag?

Upvotes: 0

KooiInc
KooiInc

Reputation: 122916

You only need a click handler on the div (in other words, use event delegation)

var tab = $("product-options-wrapper");
tab.on('click',function(e){
  e = e || event;
  if ( /^select$/i.test((e.target || e.srcElement || {}).tagName) ){
    //do stuff
  }
});

Upvotes: 0

Related Questions