[英]Make a value to be selected in the dropdown selectbox with a jQuery cookie
I am using jQuery.我正在使用 jQuery。 I have set value in cookie and I wanted a dropdown value selected.我在 cookie 中设置了值,我想要选择一个下拉值。 Here is my HTML code:这是我的 HTML 代码:
<select id="usrole" class="form-control usrole txtboxdesign" >
<option>Select Role</option>
</select>
Here is my code that populate dropdownvalue using jQuery axios:这是我使用 jQuery axios 填充下拉值的代码:
function GetAllRole() {
alert('Role Value');
axios.get(all_RoleList + '/GetAll', authToken).then(function (result) {
console.log(result);
let select = document.getElementById('usrole');
for (let i = 0; i < result.data.resultSet.length; i++) {
var optname = result.data.resultSet[i].roleName;
var optid = result.data.resultSet[i].id;
var el = document.createElement("option");
el.textContent = optname;
el.value = optid;
select.appendChild(el);
}
});
}
I have console the cookie value and I got the value.我有控制台cookie值,我得到了价值。 But I cannot set selected the dropdown value.但我无法设置选定的下拉值。 Here is my code这是我的代码
var roleid = $.cookie("roleid");
$('#usrole option[value="' + roleid + '"]').attr('selected', 'selected');
This code is not working.此代码不起作用。
Why don't you use .val()
你为什么不使用.val()
var roleid = $.cookie("roleid");
$('#usrole').val(roleid);
That will do the job i think那会做我认为的工作
Example例子
var dropdowns = [ {'Id': 1, 'value': 'Blackberry'}, {'Id': 2, 'value': 'Nokia'}, {'Id': 3, 'value': 'Xiomi'} ]; function GetAllRole() { let select = document.getElementById('usrole'); for (let i = 0; i < dropdowns.length; i++) { var optname = dropdowns[i].value; var optid = dropdowns[i].Id; var el = document.createElement("option"); el.textContent = optname; el.value = optid; select.appendChild(el); } } GetAllRole(); var roleid = 3; $('#usrole').val(roleid);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select id="usrole" class="form-control usrole txtboxdesign" > <option>Select Role</option> </select>
If your changed value is not reflected on the UI, Please try:如果您更改的值未反映在 UI 上,请尝试:
var roleid = $.cookie("roleid");
$('#usrole').val(roleid).change();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.