Using jQuery .live to populate a dropdown and selecting an item

泄露秘密 提交于 2020-01-25 01:42:05

问题


See here if you want to see what I am doing.

I can get a dropdrop list to load from a JSON source, but when I select an item the list reloads again. I know what the problem is, I just don't know the solution.

$("#RequestType").live("click", function() {
    var items = "<option selected>(Select)</option>";
    $.each(jsonRequestType, function(i, item) {
        items += "<option value='" + item.Id + "'>" + item.Title + "</option>";
    });
    $("#RequestType").html(items);
});

I know the problem is "click", but I don't know what I should use instead.

Update new related problem The only problem I have now is when the edit page loads, I have to reselect my data in each drop down. How do I get the drop down to load when I load the page?

Working Code thus far minus problem above

The display

<td><%= Html.Hidden("RequestType", Model.DayRequested.RequestType, new { Class = "RequestTypeValue" })%>
    <%= Html.DropDownList("RequestTypeDdl", new List<SelectListItem> { new SelectListItem { Text = "(Select)", Value = "" } }, new { Class = "RequestTypeDdl" })%></td>

And the script

// Get the request types for the drop down
$(".RequestTypeDdl").live("focus", function() {
    var items = "<option>(Select)</option>";
    var field = $(this);
    $.each(jsonRequestType, function(i, item) {
        items += "<option value='" + item.Id + "'";
            if ($(field).prev("input").val() == item.Id)
                items += " selected";
            items += ">" + item.Title + "</option>";
        };
    });
    $(this).html(items);
});

$(".RequestTypeDdl").live("change", function() {
    $(this).prev("input").val($(this).val());
});

回答1:


Try 'focus' or 'change', maybe.



来源:https://stackoverflow.com/questions/4411252/using-jquery-live-to-populate-a-dropdown-and-selecting-an-item

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