问题
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