我有这个下拉菜单,我想根据选择的选项在js脚本中更改变量。该变量被发送到另一个更新页面的函数。
我的html文件:
//My JS function that is trying to access the data from the dropdown
function updateDD(){
$(".sheetnameSelect").change(function(){
return $(this).find(":selected").text()
})
}
//I want to use that function to update another variable based on selected option
var selected = updateDD()
alert(selected)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class='sheetnameSelect'>
<option value="Cars">Cars</option>
<option value="Homes">Homes</option>
<option value="Planes">Planes</option>
</select>
但是功能updateDD()
并未返回所选选项(无论是在页面加载时还是在我选择其他选项时)
答案 0 :(得分:0)
您可能不需要返回值,只要select
中有更改,就可以调用该方法:
$(".sheetnameSelect").on('change', function() {
var selected = $(this).val();
createTable(selected);
});
function createTable(value) {
console.log(value);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class='sheetnameSelect'>
<option value="Cars">Cars</option>
<option value="Homes">Homes</option>
<option value="Planes">Planes</option>
</select>