gpt4 book ai didi

javascript - 如何动态获取所选选项的值并将其存储到变量中?

转载 作者:行者123 更新时间:2023-11-28 05:07:23 26 4
gpt4 key购买 nike

var temparr = [];
var arrmain = [
["E1", "RAM", "CHENNAI", "COMP", "P1"],
["E2", "RAJU", "PUNE", "ELECTRO", "P1"],
["E3", "JOHN", "KOLKATA", "MECH", "P2"]
["E4", "JOHN", "KOLKATA", "MECH", "P2"]
];
var p_id;
$(document).ready(function() {

$('#dropdown select').on('change', function() {
p_id = $('#dropdown select :selected').val();
});




for (var i = 0; i < temparr.length; i++) {
//creates option tag
$('<option/>', {
value: tempArray[i],
html: tempArray[i]
}).appendTo('#dropdown select');

}
});
<div id='dropdown'>
<select style="width:200px">

</select>
</div>

我现在有一个下拉菜单,当我更改选项时,它会从数组中获取选项,然后希望将所选选项值放入变量中。那么每当我更改选项时,如何才能将该值放入变量中

最佳答案

你就快到了。您需要迭代 arrmain 数组,而不是 temparr

您的数组中还缺少一个逗号。

试试这个

var temparr = [];
var arrmain = [
["E1", "RAM", "CHENNAI", "COMP", "P1"],
["E2", "RAJU", "PUNE", "ELECTRO", "P1"],
["E3", "JOHN", "KOLKATA", "MECH", "P2"],
["E4", "JOHN", "KOLKATA", "MECH", "P2"]
];
var p_id;
$(document).ready(function() {

$('#dropdown select').on('change', function() {
p_id = $('#dropdown select :selected').val();
alert(p_id)
});


for (var i = 0; i < arrmain.length; i++) {


$('<option/>', {
value: arrmain[i],
html: arrmain[i]
}).appendTo('#dropdown select');

}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='dropdown'>
<select style="width:200px">

</select>
</div>

关于javascript - 如何动态获取所选选项的值并将其存储到变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41627946/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com