![](/img/trans.png)
[英]How to automatically select value from drop down list in asp.net core mvc using jquery or javascript?
[英]How to access value from dynamic drop down list using Javascript/ jquery
我創建了一個動態下拉列表。 我想訪問從動態創建的下拉列表中選擇的值。 我的HTML檔案
<!DOCTYPE html>
</head>
<body>
<table align="center" cellspacing="3" cellpadding="3">
<tr>
<td>County Name: </td>
<td><select id="county"><option value="">Select county</option></select></td>
</tr>
<tr>
<td>City: </td>
<td><select id="city"><option value="">Select city</option></select></td>
</tr>
</table>
<button class="btn" onclick="doThis()"">Go</button>
</body>
我的js文件:
function doc(id){return document.getElementById(id);}
function buildCounty(){
var opts=doc('county').options;
for(var i=0;i<arr.length;i++){
opts[opts.length]=new Option(arr[i][0],arr[i][0]);
}
doc('county').onchange=function(){
this.blur();
var val=this.value;
if(!val){return;}
var co=doc('city').options;
co.length=1;
for(var j=0;j<arr.length;j++){
if(arr[j][0]!==val){continue;}
else{
var temp=arr[j][1];
for(var k=0;k<temp.length;k++){
co[co.length]=new Option(temp[k],temp[k]);
}
break;
}
}
}
}
function doThis(){
}
window.onload=buildCounty;
</script>
單擊該按鈕時,將調用js文件中存在的doThis()函數。 在該功能中,我要訪問在第二個(城市列表)下拉列表中選擇的值。
在jQuery中,您可以執行以下操作:我可以看到您對city
選項沒有任何價值。 那是您無法獲得價值的原因嗎? 如果是,那么您也需要在標記中填充值。
function doThis() { console.log($('#city').val()); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table align="center" cellspacing="3" cellpadding="3"> <tr> <td>County Name: </td> <td><select id="county"><option value="">Select county</option></select></td> </tr> <tr> <td>City: </td> <td><select id="city"><option value="SomeValue">Select city</option></select></td> </tr> </table> <button class="btn" onclick="doThis()" ">Go</button>
看起來您可能能夠在此列表中使用更多的jQuery。
首先,在Jquery中不需要此行:
function doc(id) { document.getElementyById(id); }
您可以使用CSS選擇器來使用jQuery獲取元素:
$("#id-of-element");
您甚至可以將其分配給變量:
var countyDropdown = $("#county");
此外,運行jQuery的“更好”方法之一是將script標簽放在文檔的末尾,然后等待文檔引發ready事件:
$(document).ready(function () { .... });
這是我整理的一個快速Codepen,它利用jQuery從另一個下拉列表中的選擇中動態填充一個下拉列表。 它還設置了“轉到”按鈕以在單擊時執行某些操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.