Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the class attribute value using jquery and javascript

I'm trying to get the class of the selected option and use that in a compare statement to find which class it is.

I get an undefined value. The option tag has a class set to it.

Why am I not getting a value back?

Html:

<select name="datagrid_filter" onchange="startFilter();">
    <option>All</option>
    <option disabled="true">Assignment:</option>
    <option disabled="true">Client:</option>
    <option disabled="true">Type:</option>
    <option class="type" value="Activity"> &nbsp Activity</option>
    <option class="type" value="Alert"> &nbsp Alert</option>
    <option class="type" value="Lead"> &nbsp Lead</option>
    <option class="type" value="Notification"> &nbsp Notification</option>
</select>

Javascript:

var cs1 = $("option:selected", this).attr("class");
if(cs1 == 'Type'){
    //do something
}
like image 233
user2671355 Avatar asked Sep 21 '13 13:09

user2671355


2 Answers

You should change:

onchange="startFilter();" to onchange="startFilter(this);"

and in startFilter function:

function startFilter(ele){
    var className = $("option:selected", ele).attr("class");
    if(className == 'type'){
        //do something
    }
}

Take note that, the this inside startFilter function refers to the window object, not the element you bind it to.

like image 112
Tho Avatar answered Sep 25 '22 05:09

Tho


Why don't you use hasClass jQuery API? It's very good in this case:

if($("option:selected", this).hasClass('type')){
    //do something
}

And make sure this referes to a proper object (as @undefined mentioned)
Or use:

if($("option:selected", "select[name=datagrid_filter]").hasClass('type')){
        //do something
    }

Or:

if($("select[name=datagrid_filter] option:selected").hasClass('type')){
            //do something
 }
like image 23
frogatto Avatar answered Sep 22 '22 05:09

frogatto