Internal Error
Internal Error

Reputation: 15

Nested jQuery each statement runs after the first has completed

I want to dynamically create a combo box by reading a JSON variable.

The problem is that the first $.each() statement always finishes before the second $.each() statement.

This makes the two options fall outside of the <select> element.

What am I doing wrong?

var oFields = {
    "fields": [
        {"name": "idtipopratica", "label": "ID Tipo Prat.", "type": "hidden", "visible": "true", "disabled": "false"},
        {"name": "tipologia", "label": "Tipologia", "type": "select", "selectParams": {
            "source": "list",
            "values": {"CC":"Conto Corrente","FI":"Conto Finanziario"}
        },"visible": "true", "disabled": "false"}
    ]
};
var html = '<form id="editForm" method="post" class="form-horizontal">';
$.each(oFields.fields, function (i, object) {
    switch(object.type) {
        case "select":
            html += '<select id="' + object.name + '" name="' + object.name + '"/>';
            var selectParams = object.selectParams;
            console.log(selectParams);
            if (selectParams.source === "table") {
                //console.log(selectParams.keycolumn);
            } else {
                $.each(selectParams.values, function(k,v){
                    html += '<option value="' + k + '">' + v + '</option>';
                    console.log(k+"|"+v);
                });
            }
            break;
        default:
            html += '<input type="' + object.type + '" id="' + object.name + '" name="' + object.name + '"/>';
    }
    html += '</select>';
});
html += '</form>';
$("body").html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Views: 54

Answers (1)

user4639281
user4639281

Reputation:

You've included a self-closing flag (/>) on the opening tag of the select element

html += '<select id="' + object.name + '" name="' + object.name + '"/>';

This should be

html += '<select id="' + object.name + '" name="' + object.name + '">';

(Demo)

Upvotes: 5

Related Questions