Bonesnap;11038263 wrote:
I would rewrite this and combine it into one action
Indeed. Original poster really should reconsider.
Bonesnap;11038263 wrote:
you're not adding an event in your .on() function call.
Unless I miss what code you are referring to, he is. But he has one call which is made to .change() rather than .on('change').
Bonesnap;11038263 wrote:
You'll see in my example you're adding the 'change' event to the set of matched elements (your select boxes).
Your example does add the event handler to the set of matched elements which is form, not "his select boxes". The "set of matched elements" always refer to whatever is matched in the call to the jQuery constructor
jQuery('set of matched elements').
Whenever an element's value changes a change event fires on that element. From there, it bubbles up the parentNode chain to the DOM tree root, or until a call is made to .stopPropagation() on the event object. Whenever the event reaches an element with attached event handler(s), it (they) are called.
Consider this
<form id="frm" method="post">
<div id="theDiv">
<select id="sel">
<option value="0">Select…</option>
<option value="1">1</option>
</select>
</div>
</form>
/* 1. currentTarget on the originalEvent event object (as unchanged by jQuery) will
* match the element for which the event handler is invoked, in this case #frm.
* 2. this as well as e.currentTarget will however match the element #sel, because
* jQuery invokes the event handler function for those elements that are in the
* parentNode chain and match the selector, as if the event was currently firing
* on that element.
*/
// alert: frm - sel
jQuery('#frm').on('change', 'select', function(e) { alert(e.originalEvent.currentTarget.id + " - " + this.id); });
/* when you change the select element, this is the first event handler invoked, because
* the event bubbles from the place it originates and up the chain.
*/
// alert: sel - sel
jQuery('#sel').on('change', function(e) { alert(e.originalEvent.currentTarget.id + " - " + this.id); });
/* id you add an event handler for the div and uses that to .stopPropagation, the event will
* never reach the #frm event handler, because the event bubbling is stopped before the event
* gets there. That the #frm event handler would actually be called as if the event was dispatched
* to #sel which is before #theDiv doesn't matter.
*/
// comment out this line to have the event bubbling reach the #frm element.
jQuery('#theDiv').on('change', function(e) { e.stopPropagation(); });