0

I am trying to use a function only once instead of writing it for every block of UL LI's that i need to convert to select lists. My working code is on http://jsfiddle.net/qqzB5/

I tried this but it will loop over ALL the li's, not just the one within the specific section:

$('.filterSection').each(function(){

        $('<select class="locationFilterSelect" />').appendTo(this);
        //Create Default option "Select One"
        $("<option />", {
           "selected": "selected",
           "value"   : "",
           "text"    : "Select One"
        }).appendTo('select', this);
        // Populate dropdown with menu items
        $('li', this).each(function() {
             var el = $(this);
             $("<option />", {
                 "text"    : el.text()
             }).appendTo('select', this);
        });
    });
hbowman
  • 307
  • 1
  • 6
  • 17

2 Answers2

2

You messed up with .appendTo. It takes one argument, doesn't it? And you need to use some scoping: pass select variable from outer handler to inner handler. Look at this code:

$('.filterSection').each(function(){
    var select = $('<select class="locationFilterSelect" />')
    select.appendTo(this);
    //Create Default option "Select One"
    $("<option />", {
       "selected": "selected",
       "value"   : "",
       "text"    : "Select One"
    }).appendTo(select);
    // Populate dropdown with menu items

    $(this).find('li').each(function() {
         var el = $(this);
         $("<option />", {
             "text"    : el.text()
         }).appendTo(select);
    });
});

freakish
  • 54,167
  • 9
  • 132
  • 169
1
$('.filterSection').each(function(){
        var section = $(this);
        var select =  $('<select class="locationFilterSelect" />')
       select.appendTo(section);
        //Create Default option "Select One"
        $("<option />", {
           "selected": "selected",
           "value"   : "",
           "text"    : "Select One"
        }).appendTo(select);
        // Populate dropdown with menu items       
        $(this).find('li').each(function(i,el) {
             $("<option />", {
                 "text"    : $(el).text()
             }).appendTo(select);
        });
    });

http://jsfiddle.net/tL5tD/

Brian Glaz
  • 15,468
  • 4
  • 37
  • 55