jquery – use $(this) instead of selector – Education Career Blog

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(){
$("selectname^=SELECT___").change(function() {
if ($("selectname^=SELECT___ :selected").text().indexOf("Subtract") >= 0){
alert('');
}
});
});
</script>

,

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

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

,

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.

,

$(this).filter(‘:selected’)

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

,

Try this:

$(":selected", this)

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

,

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

Leave a Comment