tags:

views:

15

answers:

1

I need to iterate through a group of select lists on my page and choose only those selects that have the selected option of "Yes".

Something like (which doesnt work):

$(".option-select option[value='yes']:selected").each(function () {
    alert($(this).attr("id"));
});
A: 

You need the .parent(), or to be safer(<optgroup> for example), .closest(), like this:

$(".option-select option[value='yes']:selected").closest('select').each(function() {
    alert(this.id);
});

Or .filter(), like this:

$(".option-select").filter(function() { return $(this).val() == "yes"; }).each(function() {
  alert(this.id);
});
Nick Craver
Thanks Nick. That works great.
StephenLewes
@StephenLewes - welcome :)
Nick Craver
Instead of iterating the collction, say i wanted to just create a jQuery collection of all the selects that, could I just do this:
StephenLewes
@StephenLewes - If you wanted an array of IDs for example, you could use `.map()` like this: `var idArray = $(".option-select").filter(function() { return $(this).val() == "yes"; }).map(function() { return this.id; }).get();`
Nick Craver
Nick, youre obviously a jQuery guru and thanks for your help. The final step of this is to pass this array back to the server using the .post() method. However I think I need to serialize the array but this doesnt seem to work. Can you help? $.post("/Quote/GetOptionPrice", idArray.serialize(), function (response) { $(".price").html(response); });
StephenLewes
@StephenLewes - You just need to pass it as an object, for example `$.post("/Quote/GetOptionPrice", { myParam: idArray }, function (response) { $(".price").html(response); });`
Nick Craver