开发者

each() on select not iterating

开发者 https://www.devze.com 2023-01-10 02:06 出处:网络
For some reason I only get to the first option when I alert out below and then it exists my entire function.It never iterates through each option:

For some reason I only get to the first option when I alert out below and then it exists my entire function. It never iterates through each option:

    function SelectAlbumOption(iAlbumID, iAlbumDropdownID)
    {
        var dropdownID = '#' + iAlbumDropdownID;

        $(dropd开发者_开发百科ownID).each(function(index, currentOption)
        {
            alert("(currentOption).attr('value'): " + $(currentOption).attr("value"));
            if($(currentOption).attr("value") == iAlbumID)
            {
                alert("matched option");
                $(currentOption).attr("selected", "yes");
                return false;
            }
        });
    }

right before this function above is called, I add options to that select, so they do exist before this function is called.


To get the options you'll need to iterate trough them, not the <select> itself, like this:

var dropdownID = '#' + iAlbumDropdownID + ' option';

Currently it's iterating over the collection of <select> elements (only one of these) and giving you it's value. If you want the <option> your selector needs to go down to those.

Also you should set selected to true or "selected" instead of "yes" (though it gets converted to true behind the scenes anyway). One other note, this: $(currentOption).attr("value") can just be this.value, no need to wrap it in a jQuery object to get that property.


As an aside, it seems you've basically re-created the .val() function, is there any reason you're not just doing this?:

$('#' + iAlbumDropdownID).val(iAlbumID);

It should have the same effect as what you're currently doing, without the alerts (assuming those are for debugging).


Are you leaving critical pieces of the code out? Because you haven't told us whether you invoke SelectAlbumOption multiple times.

Your function takes an ID and does an .each on 1 element ( unique ID ).

Did you mean to do

    var dropdownID = '#' + iAlbumDropdownID;
    $('option', dropdownID).each();

Or

$(dropdownID + ' option').each()
0

精彩评论

暂无评论...
验证码 换一张
取 消