[英]How to add dynamic selected option to a dynamically populated select list?
I'm trying to set the selected option text for a select menu to be whatever location
is - this parameter has been passed into the updateDepartment
function dynamically from a previous PHP request.我正在尝试将 select 菜单的选定选项文本设置为任何
location
- 此参数已从先前的 Z2FEC392304A5C23AC138DA22847F9 动态传递到updateDepartment
function 请求。
The AJAX function that follows calls to another PHP file to dynamically populate the #editDepartmentLocation
select menu with a list of text/value option pairs. The AJAX function that follows calls to another PHP file to dynamically populate the
#editDepartmentLocation
select menu with a list of text/value option pairs. One of the name
s in this list will always match whatever location
parameter is passed into the function.此列表中的
name
之一将始终匹配传递给 function 的任何location
参数。
I'm able to set the value of #editDepartmentName
to the name parameter as this is just a text input, however when I try to add $("#editDepartmentName").val(location)
this does not work and the selected option just defaults to the item at the top of the list, even though the value of location
is present in the list.我可以将
#editDepartmentName
的值设置为 name 参数,因为这只是一个文本输入,但是当我尝试添加$("#editDepartmentName").val(location)
这不起作用并且所选选项只是默认为列表顶部的项目,即使location
的值存在于列表中。
Is there a way to get around this?有没有办法解决这个问题?
Thanks for any help.谢谢你的帮助。
JS: JS:
function updateDepartment(name, id, location) {
$.ajax({
url: "libs/php/getLocation.php",
type: 'GET',
dataType: 'json',
success: function (result) {
console.log(result);
if (result.status.name == "ok") {
$.each(result.data, i => {
$('#editDepartmentLocation').append($("<option>", {
text: result.data[i].name,
value: result.data[i].id,
}));
});
};
},
error: function (error) {
console.log(error);
}
});
$("#editDepartmentName").val(name);
$("#editDepartmentLocation").val(location);
HTML: HTML:
<div class="form-group">
<label for="name">Name:</label>
<input type="text" value="" class="form-control" id="editDepartmentName" required>
</div>
<br>
<div class="form-group">
<label for="location">Location:</label>
<select class="form-control custom-select" id="editDepartmentLocation" required>
</select>
</div>
Ajax is async, so "editDepartmentLocation" is most likely not populated yet. Ajax 是异步的,因此很可能尚未填充“editDepartmentLocation”。 Try moving:
尝试移动:
$("#editDepartmentName").val(name);
$("#editDepartmentLocation").val(location);
Inside the success function.里面成功了function。 Or do a comparison like:
或者做一个比较,比如:
var option = $("<option>", {
text: result.data[i].name,
value: result.data[i].id,
});
if (result.data[i].id == location){
option.attr("selected", "selected");
}
$('#editDepartmentLocation').append(option);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.