选择时选择选项加载已更改

时间:2013-12-24 07:52:14

标签: javascript ajax

如何使用数据json填充选择选项

[{
    "user_id": "113",
    "employe_first_name": "Asaladauangkitamakan",
    "employe_last_name": "Nasibb"
}, {
    "user_id": "105",
    "employe_first_name": "Ryan",
    "employe_last_name": "Friday"
}, {
    "user_id": "87",
    "employe_first_name ":"hendi ",
    "employe_last_name ":"kenther"
}

当我选择更改时,请使用employe_first_name

填写另一个文本字段

2 个答案:

答案 0 :(得分:2)

试试吧 HTML

<select id='test'>
    <option value='default'>chose user</option>
</select>
<input id='get_employe_first_name' type='text' />

的javascript

$(document).ready(function(){
var data = [{ "user_id": "113", "employe_first_name": "Asaladauangkitamakan", "employe_last_name": "Nasibb" }, { "user_id": "105", "employe_first_name": "Ryan", "employe_last_name": "Friday" }, { "user_id": "87", "employe_first_name ":"hendi ", "employe_last_name ":"kenther" } ];
    $.each(data,function(i,item){
        $("#test").append("<option value='"+item.user_id+"' employe_first_name='"+item.employe_first_name+"'>"+item.employe_first_name+" "+item.employe_last_name+"</option>");
    });
    $("#test").change(function(){
        $("#get_employe_first_name").val($(this).find("option:selected").attr("employe_first_name"));
    });
});

或看看演示 jsfiddle.net/haduythuan/JFnD6/1/

答案 1 :(得分:0)

试试这个:
HTML:

<div id="test"></div>
<input type="text" id="txt"/>

Javascript:

var data = [ {"user_id":"113","employe_first_name":"Asaladauangkitamakan","employe_last_name":"Nasibb"}, {"user_id":"105","employe_first_name":"Ryan","employe_last_name":"Friday"},   {"user_id":"87","employe_first_name":"hendi","employe_last_name":"kenther"} ];
    var select = document.createElement("select");
    for(var i = 0; i < data.length; i++){
        var option = document.createElement("option");
        option.value = data[i].user_id;
        option.innerHTML = data[i].employe_first_name;
        select.appendChild(option);
    }
document.getElementById("test").appendChild(select);
select.onchange = function(){
    document.getElementById("txt").value = this.childNodes[this.selectedIndex].innerText;
};

这是DEMO