Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 407
psergiocf Avatar asked Oct 28 '25 03:10

psergiocf


1 Answers

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 );
}
like image 113
Pranav C Balan Avatar answered Oct 29 '25 17:10

Pranav C Balan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!