Kieran Kieran - 1 month ago 6
jQuery Question

JQuery each not working but by element does

I have the following code where the first line is working but the each part isn't. There's no syntax errors so I'm at a loss what isn't working.

function met() {
$("select[id*='outcome']")[0].selectedIndex = 2; # this works
$("select[id*='outcome']").each(function() {
$(this).selectedIndex = 2; # this doesn't
});
}

Answer

Because with this you are setting selectedIndex on the jQuery object

$(this).selectedIndex = 2;

needs to be

 $(this).prop("selectedIndex", 2);

or

this.selectedIndex = 2;
Comments