我正在构建一个需要动态下拉菜单的应用程序,并试图获取所生成的下拉菜单的值,但该方法无法正常工作。 我尝试了以下
get value from dynamic dropdown jquery
How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?
但是他们不为我工作
我想在ajax从数据库返回数据并将数据附加到选择元素之后,从id =“ fac_id”中获取值
$("#uni").change(function() {
var uni = $("#uni").val();
var fac = $("#fac_id");
var options;
//Make a request for a user with a given ID
if (uni !== "") {
fac.empty();
fac.append("<option id='loading'>Loading...</option>");
axios({
method: 'get',
url: 'faculties/' + uni,
responseType: 'application/json',
})
.then(function(response) {
if (response.data.length > 0) {
options = "<option>Select Faculty</option>";
response.data.forEach(element => {
options += "<option value=" + element.fac_id + ">" + element.name + "</options>";
});
fac.empty();
fac.append(options);
} else {
console.log("nothing");
fac.empty();
options += "<option value=''>No Faculty Found</options>";
fac.append(options);
}
})
.catch(function(error) {
// handle error
if (error.response.status === 401) {
console.log("Unauthorized Access");
}
})
.finally(function() {
// always executed
});
}
});
var content = [];
$('#fac_id').on("change", function() {
content.push($('#fac_id').val());
});
console.log(content);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
<label for="">University</label>
<select name="uni_id" id="uni" class="form-control">
<option value="ZOzYdjXNXibT0DtH9WrG">ANSU</option>
<option value="aQ6WWD2UX55VVlbkpdX8">FUTA</option>
<option value="8EKA7soQQgXT23z7ez4B">FUTO</option>
</select>
</div>
<div class="form-group">
<label for="">Faculty</label>
<select name="fac_id" id="fac_id" class="form-control">
<option value="">Select Faculty</option>
</select>
</div>