ASP.NET DropDownList JavaScript / jQuery获取选定值并填充项目

时间:2014-09-11 14:40:41

标签: javascript jquery html asp.net vb.net

我已经坚持了2天了。我最初使用HTMLSelect元素并取得了成功,直到我意识到我不知道如何从后面的代码中为它们赋值。以下是使用HTMLSelect元素时的代码,这些元素使页面元素按照我想要的方式运行:

<select id="cboCountry" class="autoTBComplete"/>
<select id="cboState" class="autoTBComplete" />

<script type="text/javascript">

$(document).ready(function () {

    $("#cboCountry").bind("change", ValidateCountryInput);
    $("#cboState").bind("change", ValidateStateInput);

    $.ajax({
        type: "POST",
        url: "AjaxService.asmx/GetCountryList",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        datatype:"json",
        success: function (data) {
            var d = data.d
            $(d).each(function (i) {
                $('#cboCountry').append("<option value=" + d[i] + ">" + d[i] + "</option>");
            });
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
});

function ValidateCountryInput() {
    if (CheckUSAorCAN()) {
        $.ajax({
            type: "POST",
            url: "AjaxService.asmx/GetStateList",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            datatype: "json",
            success: function (data) {
                var d = data.d
                $(d).each(function (i) {
                    $('#cboState').append("<option value=" + d[i] + ">" + d[i] + "</option>");
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
        $("[id$='cboState']").attr('style', "background:#ffd1d1; box-shadow: 0 0 20px #ff7a7a; width:64%;");
    }
    else {
        $("[id$='cboState']").val("");
        $("[id$='cboState']").attr('style', "width:5%");
        $("[id$='cboState']").classname ="autotbComplete";

    };
};

function ValidateStateInput() {
    var txt = $('#cboState').val();
    if (CheckUSAorCAN()) {
        if (txt.length > 0) {
            $("[id$='cboState']").attr('style', "width:64%");
            $("[id$='cboState']").classname = "autotbComplete";
        }
        else {
            $("[id$='cboState']").attr('style', "background:#ffd1d1; box-shadow: 0 0 20px #ff7a7a; width:64%;");
        }
    }
    else {
        $("[id$='cboState']").attr('style', "background:#ffd1d1; box-shadow: 0 0 20px #ff7a7a; width:64%;");
    };       
}

function CheckUSAorCAN() {
    var txt = $('#cboCountry').val();
    txt = toAllCaps(txt);
    txt = txt.replace("([^A-Z])+");
    return "US" == txt || "USA" == txt || "UNITEDSTATES" == txt || "CANADA" == txt;
}

function toAllCaps(string) { //jQuery toUpperCase() doesn't work on strings for IE 6-10
    if (string != null) {
        var input = string.split("")
        for (i = 0; i < input.length; i++) {
            input[i] = string.charAt(i).toUpperCase()
        };
        return input.join("")
    }
    return string
};

在完成这项工作之后,我意识到我在后面的代码中遇到了问题,特别是在以下函数中,我正在为元素分配值或从元素中检索值。我可以使用Response.Params从框中获取值,但不知道如何分配值或如何隐藏/禁用后面的代码字段,因为我不能做cboCountry.enabled = false on来自代码的select元素。如果元素是ASP.NET DropDownList,则代码可以工作(注意:我从此属性中删除了不相关的字段.cbo前缀是应用程序只是使用组合框的WinApp时的剩余部分)。

Private Property InputFieldsControl As CustomerDataFields
    Get
        Dim cdf As New CustomerDataFields       
        cdf.Country = cboCountry.Text
        cdf.State = cboState.Text
        Return cdf
    End Get
    Set(ByVal cdf As CustomerDataFields)

        If Not cboCountry.Items.Contains(New ListItem(cdf.Country)) Then
            cboCountry.Items.Add(cdf.Country)
        End If
        cboCountry.Text = cdf.Country

        If Not cboState.Items.Contains(New ListItem(cdf.State)) Then
            cboState.Items.Add(cdf.State)
        End If
        cboState.Text = cdf.State
    End Set
End Property

因为意识到HTMLSelect元素不适用于我的代码。我尝试使用DropDownLists制作相同的网页和javascript,但我没有成功。从上面更改的代码如下。注意那些是新问题的评论。具体而言,事件未触发,CheckUSAorCAN()不断从cboCountry中检索所选值的空值。

<asp:DropDownList Width="66%" CssClass="tbSkin" ID="cboCountry" runat="server" ></asp:DropDownList>
<asp:DropDownList Width="66%" CssClass="tbSkin" ID="cboState" runat="server" ></asp:DropDownList>

<script type="text/javascript">

$(document).ready(function () {       
    $.ajax({
        type: "POST",
        url: "AjaxService.asmx/GetCountryList",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        datatype:"json",
        success: function (data) {
            var d = data.d;
            $(d).each(function (i) {
                var ddlref = document.getElementById("cphContents_InputParams_cboCountry");
               addItem(ddlref,d[i]);
            });

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });

    $("#cboCountry").bind("change", onCountryChange); //does not bind or fire the event
    $("#cboState").bind("change", onStateChange); //does not bind or fire the event

});


function onCountryChange(e) {
    if (CheckUSAorCAN()) {
        $.ajax({
            type: "POST",
            url: "AjaxService.asmx/GetStateList",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            datatype: "json",
            success: function (data) {
                var d = data.d;
                $(d).each(function (i) {
                    var ddlref = document.getElementById("cphContents_InputParams_cboState");
                    addItem(ddlref, d[i]);
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
        $("[id$='cboState']").attr('style', "background:#ffd1d1; box-shadow: 0 0 20px #ff7a7a; width:64%;");
    }
    else {
        $("[id$='cboState']").val("");
        $("[id$='cboState']").attr('style', "width:5%");
        $("[id$='cboState']").classname = "autotbComplete";
    };
};

function onStateChange(e) {
    var txt = $('#cboState').val();
    if (CheckUSAorCAN()) {
        if (txt.length > 0) {
            $("[id$='cboState']").attr('style', "width:64%");
            $("[id$='cboState']").classname = "autotbComplete";
        }
        else {
            $("[id$='cboState']").attr('style', "background:#ffd1d1; box-shadow: 0 0 20px #ff7a7a; width:64%;");
        };
    }
    else {
        $("[id$='cboState']").attr('style', "background:#ffd1d1; box-shadow: 0 0 20px #ff7a7a; width:64%;");
    };
};

function CheckUSAorCAN() {
    var txt = $('#cboCountry').val();
    var e = document.getElementById("cphContents_InputParams_cboState");
    var index = e.selectedIndex; //does not work
    var strUser = e.options[e.selectedIndex]; //does not work

    if (txt != null) { //always comes up null
        txt = toAllCaps(txt);
        txt = txt.replace("([^A-Z])+");
        return "US" == txt || "USA" == txt || "UNITEDSTATES" == txt || "CANADA" == txt;
    }
    return false;
};

function addItem(ddlref, item) {
    var option1 = document.createElement("option");
    option1.text = item;
    option1.value = item;
    ddlref.options.add(option1);
};

因为在通过jQuery绑定后没有触发更改事件,所以我将它们绑定在标记代码中,如下所示:

<asp:DropDownList Width="66%" CssClass="autoTBComplete" ID="cboCountry" runat="server" onchange="onCountryChange()"></asp:DropDownList>

但是,现在onCountryChange()会触发,但是cboCountry中的值对CheckUSAorCAN()函数没有任何影响。

我没有想法。我如何使这项工作?

编辑:如果我在HTMLSelect标记上设置runat =“server”以便我可以从后面的代码访问它,它与DropDownList完全相同,除非我在其中设置onchange事件,否则事件不会触发标记。然后,每次选中的值都为null,就像DropDownList

一样

1 个答案:

答案 0 :(得分:0)

终于搞定了。我为jQuery使用了classname而不是ID。以下是未来参考的工作代码和来自谷歌的其他参考。

标记:

<select name="cboCountry" id="cboCountry" class="autoTBComplete cboCountry" runat="server" />
<select id="cboState" name="cboState" class="autoTBComplete cboState" runat="server" />

脚本:

<script type="text/javascript">

$(document).ready(function () {

    $(".cboCountry").bind("change", ValidateCountryInput);
    $(".cboState").bind("change", ValidateStateInput);

    $.ajax({
        type: "POST",
        url: "AjaxService.asmx/GetCountryList",
        contentType: "application/json; charset=utf-8",
        data: "{}",
        datatype: "json",
        success: function (data) {
            var d = data.d
            $(d).each(function (i) {
                $(".cboCountry").append("<option value=" + d[i] + ">" + d[i] + "</option>");
            });
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
});

function ValidateCountryInput() {
    if (CheckUSAorCAN()) {
        $.ajax({
            type: "POST",
            url: "AjaxService.asmx/GetStateList",
            contentType: "application/json; charset=utf-8",
            data: "{}",
            datatype: "json",
            success: function (data) {
                var d = data.d
                $(d).each(function (i) {
                    $(".cboState").append("<option value=" + d[i] + ">" + d[i] + "</option>");
                });
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
        $(".cboState").attr('style', "background:#ffd1d1; box-shadow: 0 0 20px #ff7a7a; width:64%;");
    }
    else {
        $(".cboState").val("");
        $(".cboState").attr('style', "width:5%");
        $(".cboState").classname = "autotbComplete";

    };
};

function ValidateStateInput() {
    var txt = $('.cboState').val();
    if (CheckUSAorCAN()) {
        if (txt.length > 0) {
            $(".cboState").attr('style', "width:64%");
            $(".cboState").classname = "autotbComplete";
        }
        else {
            $(".cboState").attr('style', "background:#ffd1d1; box-shadow: 0 0 20px #ff7a7a; width:64%;");
        }
    }
    else {
        $(".cboState").attr('style', "background:#ffd1d1; box-shadow: 0 0 20px #ff7a7a; width:64%;");
    };
}

代码背后:

Protected WithEvents cboCountry As Global.System.Web.UI.HtmlControls.HtmlSelect
Protected WithEvents cboState As Global.System.Web.UI.HtmlControls.HtmlSelect


Private Property InputFieldsControl As CustomerDataFields
    Get
        Dim cdf As New CustomerDataFields
        cdf.Country = Request.Params("ctl00$cphContents$InputParams$cboCountry")
        cdf.State = Request.Params("ctl00$cphContents$InputParams$cboState")
        Return cdf
    End Get
    Set(ByVal cdf As CustomerDataFields)

        If Not cboCountry.Items.Contains(New ListItem(cdf.Country)) Then
            cboCountry.Items.Add(cdf.Country)
        End If
        cboCountry.SelectedIndex = GetHTMLSelectIndex(cboCountry, cdf.Country)

        If Not cboState.Items.Contains(New ListItem(cdf.State)) Then
            cboState.Items.Add(cdf.State)
        End If
        cboState.SelectedIndex = GetHTMLSelectIndex(cboState, cdf.State)

    End Set
End Property

Private Function GetHTMLSelectIndex(elem As HtmlSelect, value As String) As Integer
    Return elem.Items().IndexOf(elem.Items.FindByText(value))
End Function