简体   繁体   中英

ASP.NET DropDownList JavaScript/jQuery getting selected value and populating items

I've been stuck on this for 2 days now. I originally used HTMLSelect elements and had success until I realized I had no idea how to assign value to them from the code behind. Here was the code when using HTMLSelect elements that made the page elements behave the way I wanted:

<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
};

After having that working, I realized I had a problem in the code behind, specifically in the following function where I am assigning values to or retrieving a value from the element. I can use the Response.Params to get the value from the box, but don't know how to assign the value or how to hide/disable the field from the code behind, since I can't do cboCountry.enabled = false on a select element from code behind. The code works if the element is an ASP.NET DropDownList (Note: I removed irrelevant fields from this property. The cbo prefix is leftovers from when the app was just a WinApp using comboboxes).

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

Since realizing that the HTMLSelect element will not work with my code behind. I tried to make the same webpage and javascript work with DropDownLists, but am not having success. The code that is changed from above is below. Pay attention to the comments as those are the new problems. Specifically the events not firing and the CheckUSAorCAN() constantly retrieving a null value for the selected value from 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);
};

Because the change events are not firing after binding via jQuery, I bound them in the markup code like so:

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

However, now the onCountryChange() does fire, but the value in the cboCountry comes back as nothing for the CheckUSAorCAN() function.

I'm out of ideas. How do I make this work?

EDIT: If I set runat="server" on the HTMLSelect markup so that I can access it from the code behind, it does the same thing as the DropDownList where the event's will not fire unless I set the onchange event inside the markup. Then the selected value is null everytime, just like it was for the DropDownList

Finally got it working. I used classname instead of ID for jQuery. Here is the working code for future reference and others coming from google.

Markup:

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

Script:

<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%;");
    };
}

Code Behind:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM