Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To find when an <code>input</code> element changes, we can simply do the following:</p> <pre><code>$('input').change(function(){ console.log('Something has changed'); }); </code></pre> <p>That will capture all the events on all the <code>input</code> elements on the page, but in your case we have the following:</p> <ul> <li>two input text fields</li> <li>4 selects</li> <li>1 textarea</li> </ul> <p>The <code>input</code> selector won't match all of those. However, <strong>don't panic</strong>! We can still do this. The clever thing is that, in the DOM, all ancestor elements are notified of events that occur on their ancestors. For example, a click on a <code>span</code> inside a <code>div</code> will notify both elements that the click has occurred.</p> <p>So in this case we just need to find a common ancestor element that contains all these elements, and capture the event on that. The obvious one to use is the <code>form</code>:</p> <pre><code>$('form').change(function(){ console.log('Something has changed'); }); </code></pre> <p><strong>However</strong> this may not be the best we can do. For instance, it would nice to have a quick way to access the element that was changed. It would also be nice if we could ensure that no other elements could trigger the function. jQuery makes this possible for us with the <code>on</code> function. This allows us to attach the handler to the <code>form</code> element and make sure that the originating element matches a selector, and then gives us a reference to that element as <code>this</code> from inside the function.</p> <p>This code could look like this:</p> <pre><code>$('form').on('change', 'input, select, textarea', function() { console.log('Something has changed in an element called ' + this.name; }); </code></pre> <hr> <p>Your edit suggests you want to be able to disable the handler at some point.</p> <p>There are two ways to do this. The first is simple and crude:</p> <pre><code>$('form').off('change'); </code></pre> <p>No more <code>change</code> events will be captured on <code>form</code>. If you want to re-enable it, however, you have to go through the whole rigmarole of re-binding the event handler. The other option is to have a variable that tells you whether the event handler should be enabled or not:</p> <pre><code>var enabled = true; $('form').on('change', 'input, select, textarea', function() { if (enabled) { console.log('Something has changed in an element called ' + this.name; } }); </code></pre> <p>You can then disable the handler by setting <code>enabled</code> to <code>false</code>, and re-enable it by setting it to <code>true</code> again.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload