BlackHatSamurai
BlackHatSamurai

Reputation: 23483

Dynamically creating dropdown with jquery not working

I'm trying to create a dropdown using javascript/jquery. Here is the code I'm using:

var trucks = response.trucks; //response from ajax request, value is 4 truck objects
var rt = $("#route_"+response.route_id);
    rt.append("<select class=\"email_route_dd\" name=\"timeslot\">")
    for(var ii = 0; ii <trucks.length; ii++){ 
        var t = trucks[ii]; //truck object
        if(ii+1 == trucks.length){
            console.log("Last"); 
            rt.append("<option name=\"\" class=\"driver\" value=\""+t.truck_id+"\" email=\""+t.driver_email+"\">"+t.driver+"</option>"); 
        }else{
            rt.append("<option name=\"\" class=\"driver\" value=\""+t.truck_id+"\" email=\""+t.driver_email+"\">"+t.driver+"</option>"); 
        }
    }; 
rt.append("</select>"); 

This code is outputing the following code:

enter image description here

The above image is what I get when I inspect the element with Chrome.

The output is not displaying the dropdown content after the request. The dropbox is there, but none of the content is in it.

Upvotes: 0

Views: 1303

Answers (2)

PSL
PSL

Reputation: 123739

Try this way instead:

var rt = $("#route_"+response.route_id), 
    $select = $("<select>", {'class' : 'email_route_dd', 'name':'timeslot'}); //Create select as a temp element and append options to this.

    for(var ii = 0; ii <trucks.length; ii++){ 
        var t = trucks[ii]; //truck object
             option = "<option name=\"\" class=\"driver\" value=\""+t.truck_id+"\" email=\""+t.driver_email+"\">"+t.driver+"</option>"; 

        $select.append(option);
    }; 
rt.append($select); 

Or this way, using data-* attributes and array.map and more readeable.

var rt = $('body'),
    $select = $("<select>", {
        'class': 'email_route_dd',
            'name': 'timeslot'
    }); //Create select as a temp element and append options to this.

$select.append($.map(trucks, function (t) {
    return $('<option>', {
            'class': 'driver',
            'value': t.truck_id,
            'data-email': t.driver_email,
            'text': t.driver
    });
}));

rt.append($select);

With this you append to the DOM in the end only rather than on the loop.

Demo

Upvotes: 2

charlietfl
charlietfl

Reputation: 171679

You append a <select> to the element. Then instead of appending <option> tags to the <select> you also append those to the same element

Try:

rt.find('select')append("<option name...

Upvotes: 2

Related Questions