Add optgroup with options to select with jQuery

Baseem Najjar picture Baseem Najjar · Nov 26, 2012 · Viewed 24.2k times · Source

my question is simple but yet I didn't find a clear example of doing that. I'm trying to add optgroup for a select and fill it with options using jquery for some reason it's not working. this is my code:

$('#ptype').change(function() {
        $.post(
                   "/sell/site/index/categories", 
                   {
                      'parent_id': $('#ptype').val()
                   }, 
                   function(response){
                       var categories = $.parseJSON(response);

                       $('#sub_category').empty();
                        $.each(categories, function (index) {

                            var optgroup = $('<optgroup/>');

                            $.each(this.children, function (index) {
                                optgroup.add($("<option></option>")
                                            .attr("value",index)
                                            .text(this)); 
                            });

                            $("#sub_category").append(optgroup);

                        });

                        $("#sub_category").multiselect('refresh'); //refresh the select here
                    }
                );
        });

Any help would be greatly appreciated! Thanks!

Answer

Baseem Najjar picture Baseem Najjar · Nov 26, 2012

Ok so I figured out the solution myself in the end, however, thanks for the useful tips from you guys. here's the working code:

$('#ptype').change(
            function() {
                $.ajax({
                  type: 'POST',
                  url: "/sell/site/index/categories",
                  data: { 'parent_id': $('#ptype').val() },
                  success: function(data){ updateCategories(data); },
                  dataType: 'json'
            })
        }
    );

function updateCategories(categories){
         $('#sub_category').empty();
         $.each(categories, function (index) {
            var optgroup = $('<optgroup>');
            optgroup.attr('label',categories[index].name);

             $.each(categories[index].children, function (i) {
                var option = $("<option></option>");
                option.val(i);
                option.text(categories[index].children[i]);

                optgroup.append(option);
             });
             $("#sub_category").append(optgroup);

         });

         $("#sub_category").multiselect('refresh'); //refresh the select here
}