Abhijit Borkakoty Abhijit Borkakoty - 4 months ago 18
jQuery Question

this keyword instead of event.target?

I have this code using jQuery:

$( 'form' ).submit(function( event ) {
var $input = $(event.target).find('input');
var comment = $input.val();
});


Can we use $(this) instead of the event.target here ?

Our overall task is to find the input element and its value

Here goes the replaced code:

$( 'form' ).submit(function(event) {
var $input = $(this).find('input');
var comment = $input.val();

});

Answer

Yes you can definitely use $(this) here:

$( 'form' ).submit(function(event) {
    var $input = $(this).find('input');
    var comment = $input.val();
});

When jQuery calls a handler, the this keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector. (Note that this may not be equal to event.target if the event has bubbled from a descendant element.)

To create a jQuery object from the element so that it can be used with jQuery methods, use $( this ).

Comments