如何为异步加载的下拉列表分配唯一值

时间:2018-12-24 00:48:04

标签: javascript api asynchronous drop-down-menu

我已成功从API作为下拉列表加载了数据,并且我希望在选择时获取每个选项的值。如何为每个选项分配唯一值?还有如何获得所选值?

HTML

<div class="cur-conv-container">
    <select id="conv_from"></select>
    <input type="number" name="" id="num_from">
    <br><br>
    To: 
    <select id="conv_to"></select>
    <br><br>
    <a href="#" id="conv-btn" class="btn btn-warning btn-cur-conv " onclick="convert()">Convert</a>
</div>

JAVASCRIPT

<script type="text/javascript">

function loadCurrency(){ 
    var url = "https://free.currencyconverterapi.com/api/v6/currencies";
    var currency ;
    var allCurr;
    var currencyFrom = document.getElementById("conv_from");
    var currencyTo = document.getElementById("conv_to");

    var xhttp = new XMLHttpRequest;

    xhttp.onreadystatechange = function(){
        if(xhttp.readyState==4 && xhttp.status==200){
            currency = JSON.parse(xhttp.response);
            allCurr = currency.results;
            for(x in allCurr){
            currencyFrom.innerHTML += "<option>" + x + "</option>";
            currencyTo.innerHTML += "<option>" + x + "</option>";
            }

        }
    }
    xhttp.open("GET", url, true);
    xhttp.send();
}
</script>

1 个答案:

答案 0 :(得分:1)

如果我不能正确理解您的问题,那么您想提取从API返回的每种货币项目的id,并将其用于您的<select>选项的值。

这可以通过对onreadystatechange处理程序进行以下更改来实现:

xhttp.onreadystatechange = function(){
    if(xhttp.readyState==4 && xhttp.status==200){
        currency = JSON.parse(xhttp.response);
        allCurr = currency.results;
        for(x in allCurr){

        // Extract the currency item for current key "x"
        var currency = allCurr[x];

        // Extract currency id from current currecny item
        var currencyId = currency.id;

        // Use currencyId as value for select options being added
        currencyFrom.innerHTML += 
        "<option value='" + currencyId + "'>" + x + "</option>";
        currencyTo.innerHTML += 
        "<option value='" + currencyId + "'>" + x + "</option>";
        }

    }
}