0

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.

2 Answers 2

2

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...
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

@user2310289 It doesn't i noticed and as you were commenting i was removing it... :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.