[英]Getting the “value” out of a dynamically generated drop down list using JavaScript
当我使用静态下拉列表时,我可以获取值,但是一旦更改为动态生成的列表,值始终为空。
有人有想法么? 甚至有可能从动态元素中获取价值吗?
JS:
$('#input_baseUrl').ready(function(){
var newSelect=document.createElement('select');
var selectHTML="";
for(var count=0; count<services.length; count=count+1){
var tempString = services[count].split("/");
var serviceName = tempString[3];
selectHTML+= "<option value='"+services[count]+"'>"+serviceName+"</option>";
}
//iniatilize a new select with the data we provided
newSelect.innerHTML= selectHTML;
//find the DOM element that is called input_baseURL
document.getElementById("input_baseUrl").appendChild(newSelect);
});
function setURL() {
var url = document.getElementById("input_baseUrl").value;
alert($('#input_baseUrl').val()); // not sure if jQuery will work here but I have to try
window.alert("THE URL is: " + url);
var element = document.getElementById("input_baseUrl");
var strUser = element.options[element.selectedIndex].value;
window.alert("Third option is: " +strUser);
}
HTML:
<form id='api_selector'>
<div class='input' id="input_baseUrl" onchange="setURL()" name="baseUrl" type="text"></div>
<div class='input'><input placeholder="api_key" id="input_apiKey" name="apiKey" type="text"/></div>
<div class='input'><a id="explore" href="#">Explore</a></div>
</form>
是的,有可能。 但是您必须使用更详细的选择器:
$('#input_baseUrl select option:selected').val();
但是我认为您的HTML在下一行有问题,您是说这是两个标签,一个div
内的input
吗?
<div class='input' id="input_baseUrl" onchange="setURL()" name="baseUrl" type="text"></div>
要解决此问题,请将其分成两个标签,并给div
一个id
:
<form id='api_selector'>
<div class='input' id="div_baseUrl">
<input id="input_baseUrl" onchange="setURL()" name="baseUrl" type="text"/>
</div>
...
</form>
然后,您可以从ready()
函数将newSelect
添加到div
:
document.getElementById("div_baseUrl").appendChild(newSelect);
之后,您的setUrl()
函数可以是:
function setURL() {
var url = $('#input_baseUrl').val();
var strUser = $('#div_baseUrl select option:selected').val();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.