0

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();

});
Elyor
  • 5,396
  • 8
  • 48
  • 76

1 Answers1

1

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 ).

Dhara Parmar
  • 8,021
  • 1
  • 16
  • 27