Search code examples
javascripthtmljsonprototypejs

Filling out Combobox Using JSON value


Hello I have a following html

<select id="fld_base_profile_id" defaultValue="-1" class="m-wrap span10" field="fld_base_profile_id" appEditor="true"></select>

I have this in my ajax

$result['analyze_type'][]   = array ("id" => $row[idatabase::FIELD_ID], "name" => $row[idatabase::FIELD_PROFILE_NAME]);
echo json_encode($result);

and in js part (by the way i'm using Prototype.js) :

var JSON    = transport.responseText.evalJSON();

In console, my JSON.analyze_type looks like this

Array[1]
0: Object
id: "939"
name: "Reaktif İndüktif Kontrolü Ana Profili"

The question is, how can i parse this JSON data so it can change my html like

<option value="id">name</option>  ??

EDIT: Solution:

this.baseProfile    = $("fld_base_profile_id");

var JSON    = transport.responseText.evalJSON();
    this.type   = JSON.analyze_type;
    for(var i = 0; i < JSON.analyze_type.length; i++) {
        var profile = JSON.analyze_type[i];
        var opt     = document.createElement("option");
        opt.value   = profile.id;
        opt.text    = profile.name;
        this.baseProfile.appendChild(opt);
    }

Solution

  • Try this

    var el = document.getElementById('fld_base_profile_id');
    
    for(var i = 0; i < JSON.length; i++) {
        var profile = JSON[i],
            opt = document.createElement("option");
    
        opt.id = profile.id;
        opt.value = profile.name;
        el.appendChild(opt);
    }​