Programmatically create select list

Viewed 106524

Does anyone know of a technique to programmatically create an HTML select list including options using JQuery?

8 Answers

I think it's simpler.IMHO.

 arr.map(x => ($("YOUR SELECTOR").append(`<option value="${x}">${x}</option>`)));

Here is another version of an answer to the question using ajax to fetch a json response used to create the select list with key value pairs

        $.ajax({
        type: 'post',
        url: 'include/parser.php',
        data: {                     
            mode: 'getSubtypes',
            type: type
        },
        success: function (response) {
            var mySubtype = document.getElementById("Component");
            var components = $.parseJSON(response);

            var selectList = document.createElement("select");
            selectList.id = "subtype";
            selectList.name = "subtype";
            mySubtype.appendChild(selectList);
            $('#subtype').append('<option value="">Select ...</option>');
            $.each(components, function(k, v) {
                var option = new Option(v, k); 
                $('#subtype').append($(option));               
            });
        }
    });        
Related