在刷新后使用jQuery在选择下拉列表中保持选择的选项 [英] Keeping selected an option in select dropdown with jquery after refresh

查看:170
本文介绍了在刷新后使用jQuery在选择下拉列表中保持选择的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小脚本,可以重新加载包含聊天室中用户昵称的选择.当某人单击选择时,javascript刷新它,从php页面重新填充该选项,以添加已登录的人员并删除已注销的人员. 该脚本在重新加载select时可以正常工作,但是我希望它可以避免如果用户再次单击select来刷新列表,并且该脚本没有保留正确的选项,则不会丢失先例中的selected选项.除了jquery的那部分之外,所有代码都可以正常工作.

I have small script that reloads a select containing the nicknames of the users in a chatroom. When someone clicks the select, the javascript refreshes it, repopulating the option from a php page to add people that have logged in and removing those who logged out. The script works properly on reloading the select, but I want it to avoid losing the precedent selected option if a user clicks the select another time to refresh the list, and the script doesn't keep the correct option. All the code works properly, except that part of the jquery.

JS(页面上当然也有jquery库):

The JS (the jquery library is of course also on the page):

<script type="text/javascript">
  $(document).ready(function() {
    $("#Users").focusin(function() {
      var UsersSelect = $('#Users').val();
      $("#Users").load("users.php");
      $('select[name="Users"]').val(UsersSelect);
    });
  });
</script>

html/php网页:

The html/php webpage:

<div id="UserList" name="UserList">
<select name="Users" id="Users">
<?
$queryprep = "select name FROM users";
$query = $PDO->prepare($queryprep);
$query->execute();
while($rs = $query->fetch()) {
    echo "<option value=".$rs['name'].">".$rs['name']."</option>";
}
$query = null;
?>
</select>
</div>

users.php页面:

The users.php page:

<select name="Users" id="Users">
<?
$queryprep = "select name FROM users";
$query = $PDO->prepare($queryprep);
$query->execute();
while($rs = $query->fetch()) {
    echo "<option value=".$rs['name'].">".$rs['name']."</option>";
}
$query = null;
?>
</select>

感谢您的回答.

推荐答案

AJAX是异步的,因此您尝试在填充数据之前尝试重置该值.替换选项后,选择项将再次丢失值

AJAX is asynchronous so you are trying to reset the value before the data will be populated. Once the options are replaced the select will lose the value again

使用load()complete callback

$("#Users").focusin(function() {
    var $select=$(this),  UsersSelect = $select.val();
    $select.load("users.php", function(){
       /* new html exists now s we can set value*/
       $select.val(UsersSelect);
    });
})

这篇关于在刷新后使用jQuery在选择下拉列表中保持选择的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆