Reputation: 4320
I'm populating my select list/drop on demand and for some reason the list disappears on MouseUp.
Code to populate the list:
<select id="UserList" name="UserList" onclick="getCountries()">.....</select>
.
.
.
function getCountries() {
$.post("/Users/GetUsersJson/", { id: userId },
function (result) {
$.each(result, function (item) {
$("#UserList").append(
$("<option></option>").text(result[item].UserName).val(result[item].Id)
);
});
}, "json");
}
When I click on the list it gets populated just fine however when I release the mouse button it closes without letting me select anything on the list. I can't figure out what's happening.
Any clues ?
Upvotes: 1
Views: 3037
Reputation: 14245
HTML:
<select id="UserList" name="UserList"></select>
jQuery:
$(document).ready(function(e){
$('#UserList').click(function(e){
if($(this).children().length == 0){
$.post("/Users/GetUsersJson/", { id: userId },
function (result) {
$.each(result, function (item) {
$("#UserList").append("<option val='"+result[item].Id+"'>"+result[item].UserName+"</option>");
});
}, "json");
}
});
});
Try the above:
The reason the popup disappears is because when you click the dropdown, it will make another GET request for the JSON data and re-populate your SELECT. I added a check for children()
length, to make sure there are no <option>
tags inside.
Upvotes: 0
Reputation: 35117
I can't see anything that would cause your drop down list to disappear so I'd suggest putting in some alert boxes so you can determine precisely which line triggers the issue. That said, you should be aware that this is possible with the jquery each method.
function getCountries() {
$.post("/Users/GetUsersJson/", { id: userId },
function (result) {
$.each(result, function (index, item) {
$("#UserList").append(
$("<option></option>").text(item.UserName).val(item.Id)
);
});
}, "json");
}
Makes your code a little bit easier to read.
Upvotes: 1