0

I would like to be able to loop through and log each option available in a select dropdown box. I'm not sure how to do this while using $(this).

This is what I have.

$('select').each(function(){
    $(this).find('options').each(function(){
        var boxOpt = $(this).text();
        console.log(boxOpt);
    });
});

It currently outputs nothing. I would like to be able to do something like: $(this + ' options').each(function(){...}); but this is not working either.

I have tried $(this).find(), $(this).children() and some other variations, but I'm not sure what to do now.

Any suggestions? Thank you

4

2 回答 2

4

options should be option. You can just add it to the selector string:

$('select option').each(function(){
    var boxOpt = $(this).text();

    console.log(boxOpt);
});
于 2013-05-21T00:01:23.767 回答
2

Here's how to do it in Vanilla JS:

var tags = document.getElementsByTagName('select'), l = tags.length, i, opts, m, j;
for(i=0; i<l; i++) {
    opts = tags[i].options;
    m = opts.length;
    for( j=0; j<m; j++) {
        console.log(opts[j].text);
    }
}
于 2013-05-21T00:02:17.963 回答