[英]Select box losing selected option when refreshed
I'm trying to create a select box that refreshes its options when selected by the user, but I'm encountering a problem that I can't figure ho to solve. 我正在尝试创建一个选择框,当用户选择该框时会刷新其选项,但是遇到一个无法解决的问题。 Being still a beginner with jquery I've already asked an advice for the same program: Keeping selected an option in select dropdown with jquery after refresh .
还是jquery的初学者,我已经对同一个程序提出了建议: 在刷新后使用jquery在select下拉列表中选择一个选项 。
Following the suggestion now it works almost completely, but I'd like the dropdown to behave exactly as a non dynamic one, keeping the selected option when opened, except for having the options list also refreshed: now it “almost” keeps the value selected (it retains it in the dropdown) but resets to the first option when the element lose focus to others in the page and I don't know how to resolve the problem. 现在,按照建议,它几乎可以完全工作,但是我希望下拉列表的行为完全像一个非动态的一样,在打开时保持选定的选项,除了刷新选项列表:现在,“几乎”保持选定的值(将其保留在下拉菜单中),但是当该元素失去对页面中其他对象的关注并且不知道如何解决该问题时,它将重置为第一个选项。 I tried to pass a variable with ajax to the php page to have it selected on refresh, but it still resets when focus is change.
我试图将带有ajax的变量传递给php页面,以使其在刷新时被选中,但是当焦点改变时,它仍然会重置。
The JS code: JS代码:
$(document).ready(function() {
$("#UsersDiv").focusin(function() {
var UsersSelect = $('#UsersList').val();
$.get(
"userlist.php",
{ UserSelect1: UsersSelect },
function(data) {
$('#UsersList').html(data);
}
);
})
$('#UsersList').val(UsersSelect);
});
The html page: html页面:
<div name="UsersDiv" id="UsersDiv">
<select name="UsersList" id="UsersList">
<option value="User1">User1</option>
<option value="User2">User2</option>
</select>
</div>
The php file (the “users” array is in place of the sql query, both work properly): php文件(“用户”数组代替sql查询,两者均正常工作):
$UserSelect1 = $_GET['UserSelect1'];
$users=array( 'User1','User2','User3','User4','User5');
echo '<select name="UsersList" id="UsersList">';
foreach($users as $list):
echo '<option value="'.$list.'" ';
if ($UserSelect1 == $list) {
echo 'selected=selected';
}
echo '>'.$list.'</option>';
endforeach;
echo '</select>';
Thanks to everyone for the answers. 感谢大家的答案。
$("#UsersDiv")
than you assigning this 比你分配这个
$select=$(this) // $select is $("#UsersDiv");
and than you are trying to get val from div 而且比你想从div获取val
UsersSelect = $select.val() // $select.val() is undefined
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.