如何使用jquery在列表框中选择项目的默认选择

How to select the default selection on the item in my list box using jquery

本文关键字:选择 项目 默认 何使用 jquery 列表      更新时间:2023-09-26

使用下面的代码,我将代码插入到列表框中。

<select id="lstCodelist" size="17" name="lstCodelist" style="width:100%;height:280px;background-color:#EFEFFB;"></select>

使用这段代码,我在lstCodelist框中显示数据。

$.fn.fillSelectDD = function (data) {
    return this.clearSelectDD().each(function () {
        if (this.tagName == 'SELECT') {
            var dropdownList = this;
            $.each(data, function (index, optionData) {
                var option = new Option(optionData.Text, optionData.Value);
                 if ($.browser.msie) {
                    dropdownList.add(option);
                }
                else {
                    dropdownList.add(option, null);
                }
            });
        }
    });
}

这是我要调用的函数,用于从一个列表框插入到另一个列表框。

function DoInsert(ind) {
            var sourceIndex = $("#lstAvailableCode").val();
            var targetIndex = $("#lstCodelist").val();
            var success = 0;
            var rightSelectedIndex = $("#lstCodelist").get(0).selectedIndex;
            var functionName = "/Ajax/SaveCodeforInsert";
            if (ind == "plan") {
                functionName = "/Ajax/SaveCodeforInsertForPlan";
            }
            $.ajax({
                type: "POST",
                traditional: true,
                url: functionName,
                async: false,
                data: "ControlPlanNum=" + $("#ddControlPlan").val() + "&LevelNum=" + $("#ddlLevel").val() + "&ColumnNum=" + $("#ddlColumn").val() + "&SourcbaObjectID=" + sourceIndex + "&TargetbaObjectID=" + targetIndex + "&userID=<%=Model.userID%>",
                dataType: "json",
                error: function (data) {
                    alert("Error Adding Code");
                    FinishAjaxLoading();
                },
                success: function (data) {
                    if (data == 0) { success = 1; } else { success = data; }
                    // $("#lstCodelist option").eq(1).attr('selected', 'selected')
                    $("#lstCodelist option:first-child").attr("selected", "selected");
                    FinishAjaxLoading();
                }
            });

但是在我的成功函数中使用此代码时,我无法选择分配或突出显示或选择此lstCodelist框。

// $("#lstCodelist option").eq(1).attr('selected', 'selected')
                        $("#lstCodelist option:first-child").attr("selected", "selected");

但它不工作在我的代码现在是我在这里做错了什么?

谢谢

我认为在选择中,只需使用$("#select_id").val(default_val);来选择您需要的值。

http://api.jquery.com/val/