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
  • 79,297
  • 15
  • 120
  • 134
1252748
  • 14,597
  • 32
  • 109
  • 229

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
  • 86,271
  • 21
  • 138
  • 164
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
  • 79,297
  • 15
  • 120
  • 134
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,950
  • 5
  • 68
  • 101
-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,610
  • 8
  • 34
  • 50