user357034
user357034

Reputation: 10981

use $(this) instead of selector

How would I use $(this) instead of the full selector in the code below in the "if" statement. I tried a few different combination of "this" usage and none worked. Among them are...

if ($("this :selected").text().indexOf("[Subtract") >= 0){
if ($(this" :selected").text().indexOf("[Subtract") >= 0){

I am sure its gotta be something really simple, I just cannot figure it out today.

<script type="text/javascript" language="javascript">
$(document).ready(function(){
$("select[name^=SELECT___]").change(function() {
if ($("select[name^=SELECT___] :selected").text().indexOf("[Subtract") >= 0){
alert('');
}
});
});
</script>

Upvotes: 1

Views: 147

Answers (5)

user113716
user113716

Reputation: 322502

You can specify this as the context of the selector:

$(":selected",this)

But it ultimately just gets turned around into @Gumbo's answer. So that would be a little more efficient.


Ultimately, I wouldn't use either. If you actually need to selected <option>, this would be another approach:

this.options[ this.selectedIndex ].text.indexOf(...;

Since this is the <select> element, you use its options property which stores an Array of the options, and its selectedIndex property to get the selected one from the options.

Then you use the <option> element's text property to get the text.

More efficient this way.

Upvotes: 3

Jim
Jim

Reputation: 1061

The jQuery 'is' selector seems to do what you want although I haven't checked it: http://api.jquery.com/is/

if($(this).is(":selected").text().indexOf("[Subtract") >= 0){ ... }

Upvotes: 0

Timothy S. Van Haren
Timothy S. Van Haren

Reputation: 8966

Try this:

$(":selected", this)

This limits the ":selected" selector to the context of the "this" object. More info here.

Upvotes: 2

Tudor
Tudor

Reputation: 4164

$(this).filter(':selected')

http://api.jquery.com/filter/

Upvotes: 2

Gumbo
Gumbo

Reputation: 655269

Use the find method on $(this) to find specific elements that are descendants of this:

$(this).find(":selected").text().indexOf("[Subtract")

Upvotes: 3

Related Questions