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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With