1

if i am looping through some jquery objects that are select dropdowns, how can I get the class of the selected option using jquery's $(this)?

elems.each(function(idx, elem) {
    if ($(this).is('select')){
        console.log($(this, "option:selected"))
    }
});

does not seem to work.

Selvakumar Arumugam
  • 78,145
  • 14
  • 119
  • 133
1252748
  • 13,412
  • 30
  • 97
  • 213

4 Answers4

5
​elems.each(function(idx, elem) {
    var ref = $(this); // caching $(this)
    if( ref.is('select') ) {
        console.log( ref.find('option:selected') );

        // OR in jQuery Context format
        console.log( $('option:selected', ref) ); // this format internally 
                                                  // called .find() method

        // to get the class
        console.log( ref.find('option:selected').attr('class') );
    }
})​;
thecodeparadox
  • 84,459
  • 21
  • 136
  • 161
3

You are almost there except that the order in which you have passed the argument are not correct. See below,

elems.each(function(idx, elem) {
    if ($(elem).is('select')){
        console.log($("option:selected", elem));
    }
});

$("option:selected", this) in which the first argument is the selector and 2nd argument is the context.

Note: The .each 2nd argument is the element itself, so you can use elem instead of this

DEMO: http://jsfiddle.net/MUC6H/1/

Selvakumar Arumugam
  • 78,145
  • 14
  • 119
  • 133
2

how can I get the class of the selected option

if ($(this).is('select')){
        console.log($(this).find("option:selected").attr("class"));
    }

http://jsfiddle.net/DWEY4/

Rafay
  • 30,714
  • 5
  • 66
  • 99
-1

Have you tried the hasClass function?

elems.each(function(idx, elem) {
    if ($(this).hasClass('select')){
        console.log($(this, "option:selected"))
    }
});

Looking at it further, i think your original method will work too if you add a . class identifier

elems.each(function(idx, elem) {
    if ($(this).is('.select')){
        console.log($(this, "option:selected"))
    }
});
jamis0n
  • 3,270
  • 7
  • 31
  • 47