Lievcin
Lievcin

Reputation: 938

looping through select tag with jQuery

I'm trying to loop through a select tag, with multiselect. I'm new to jQuery and I found this code, however I need to loop through all of the option tags, checking whether the option is selected or not, as I need to do something in both cases.

$('.multiselect').change(function () {
  $('.multiselect option:selected').each(function () {
    //do something
  });
}).trigger('change');

I was trying to make it into something more like this:

$('.multiselect').change(function () {
  $('.multiselect').each(function () {
    $('option', this).each(function() {
      if ('option':selected == true) {
        //do something
      }
      else {
        //do something else
      }
    });
  });
}).trigger('change');

But this doesn't work. Can someone suggest a good approach?

Upvotes: 1

Views: 563

Answers (2)

jonepatr
jonepatr

Reputation: 7809

$(".multiselect").change(function () {    
  $(".multiselect option").each(function(){  
    if($(this).attr("selected") == "true"){  
      // do something  
    } else {
      // do something else
    }
  }
}

should work..

Upvotes: 1

Ry-
Ry-

Reputation: 224942

$(".multiselect").change(function() {
    $("option", this).each(function() {
        if(this.selected) {
             // This one is checked
        } else {
             // This one is not checked
        }
    }
});

Should work, I think.

Upvotes: 4

Related Questions