psergiocf
psergiocf

Reputation: 1617

jQuery change and click events

Binding events to an element should be something like:

$( document ).on( 'change', '#mySelect', showEvent );
$( document ).on( 'click', '#mySelect', showEvent );

function showEvent() {
  console.log( event.target );
}

But by doing a simple test as shown below, binding the change and click events to the object mySelect they are triggered on different elements (change only by changing the select and the click by clicking anywhere on the document).

var mySelect = $( '#mySelect' );

$( document ).on( 'change', mySelect, showEvent );
$( document ).on( 'click', mySelect, showEvent );

function showEvent( event ) {
  console.log( event.target );
}

Two questions:

  1. How does the change event work? By the documentation it shouldn't work because the selector must be a string:

A selector string to filter the descendants of the selected elements that trigger the event.

  1. It souldn't work but, if the change works, why doesn't the click?

Upvotes: 4

Views: 1401

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115242

selector
Type: String A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.

Taken from http://api.jquery.com/on/

You are using the selector as a jQuery object, this method is mainly using for event delegation for binding event to dynamically generated element. So you can bind event directly to the jQuery object as

var mySelect = $( '#mySelect' );

mySelect.on( 'change', mySelect, showEvent )
        .on( 'click', mySelect, showEvent );

function showEvent() {
  console.log( event.target );
}

If it's dynamically generated then remove the $ wrapping just provide it as string

var mySelect = '#mySelect';

$( document ).on( 'change', mySelect, showEvent );
$( document ).on( 'click', mySelect, showEvent );

function showEvent() {
  console.log( event.target );
}

Upvotes: 2

Related Questions