繁体   English   中英

在使用JavaScript动态填充的下拉列表中获取所选值

[英]Get selected value in dropdown list that is populated dynamicaly using JavaScript

在这里,当我选择一种货币时,我试图显示一个国家标志,但是当我使用API​​中的数据时,我的代码不起作用

JS

function createDoll(userChoice) {
var output = document.getElementById("display_here");
output.innerHTML = "";

var links = [
    "https://simplytest.co.za/fxpaymaster/wp-content/uploads/2019/09/usd-flat.jpg",
    "https://simplytest.co.za/fxpaymaster/wp-content/uploads/2019/09/sa-flag.jpg"
];
var img1;
var e=document.getElementById("currency-from");
var strUservalue = e.options[e.selectedIndex].value;
var strUsertext = e.options[e.selectedIndex].text;
if(strUservalue=='USD')
{
     img1 = '<img src="' + links[userChoice] + '">';
}

var choices = ["USD", "ZAR"];
var sentence = choices[userChoice]
var img1 = '<img src="' + links[userChoice] + '">';

output.innerHTML = sentence +img1 +strUservalue;

这是我的HTML

<body>
  <input type="text" name="" id="currency-from-text" class="form-control"
                            placeholder="Transferring how much?" value="1">
                            <select class="populate-currencies" id="currency-from" onchange="createDoll(this.value)">
                        <option value="USD" id="curr">USD</option>

                        </select>
</body>

我想如果有人选择美元,则显示美国国旗,如果他们选择英镑,则显示英国国旗

links[USD]不存在。 将您的links数组更改为关联数组:

var links = {
   "USD": "https://simplytest.co.za/fxpaymaster/wp-content/uploads/2019/09/usd-flat.jpg",
   "SA": "https://simplytest.co.za/fxpaymaster/wp-content/uploads/2019/09/sa-flag.jpg"
};

<select class="populate-currencies" id="currency-from" onchange="createDoll(this.value)">
  <option value="USD">USD</option>
  <option value="SA">SA</option>
</select>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM