Keeping selected an option in select dropdown with jquery after refresh

隐身守侯 提交于 2019-12-13 05:33:10

问题


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.

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>

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>

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>

Thanks for the answers.


回答1:


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

Use the complete callback of load()

$("#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);
    });
})


来源:https://stackoverflow.com/questions/20589466/keeping-selected-an-option-in-select-dropdown-with-jquery-after-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!