Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending $(this) on an onchange on the current element

I have this html

<select class="category" style="margin-bottom: 5px;" onchange="getProducts('standard_product');">

and as you can see the onchange calls the getProducts function. I want to know if there is a way to sent in this like

<select class="category" style="margin-bottom: 5px;" onchange="getProducts('standard_product', $(this));">

which i would hope would be associated to the current select

like image 776
Matt Elhotiby Avatar asked Jun 13 '11 19:06

Matt Elhotiby


1 Answers

If you're trying to set the value of this in your function, you can use .call:

onchange="getProducts.call(this, 'standard_product');"

Now in your getProducts function, this will be the element that received the event.

function getProducts( prod ) {

    alert( this );  // the <select> element

}

You can also pass along the event object:

onchange="getProducts.call(this, 'standard_product', event);"

...and reference it in your function:

function getProducts( prod, e ) {

    alert( this );  // the <select> element

    alert( e.type );  // the event type

}

EDIT: As noted by @Cybernate, this is setting the DOM element to this. You'll need to wrap it in your getProducts function $(this), or set it as such in your inline handler.

Though setting this to the element itself is more in line with typical event handler behavior.


EDIT: To further explain what .call does, it allows you to manually set the value of this in the function you're calling.

Take this function, which simply alerts this:

function some_func() {

    alert( this );

}

Calling it in a basic manner (in a browser) makes this reference the DOM Window.

some_func();  // the alert will be DOM Window

But now lets invoke using .call, and setting the first argument to 123.

some_func.call( 123 );  // the alert will be 123

You can see that now the alert shows 123. The function hasn't changed, but the value of this has because we've manually set it using .call.

If you have additional arguments to send, you just place them after the thisArg.

function some_func( arg1 ) {

    alert( this );
    alert( arg1 );

}

some_func.call( 123, 456 );

The this alert will be 123, and the next argument you send will be set to the arg1 parameter, so arg1 will be 456.

So you can see that call basically slices off your first argument you send, sets it as the value of this, and sets the remaining arguments as your normal arguments associated with your function parameters.

like image 101
user113716 Avatar answered Oct 20 '22 01:10

user113716