How can I respond to the selected item in a DropDownList using jQuery?

I have a dropdownlist with several items in it. In anticipation of responding to the selection the user makes, I added the following "proof-of-concept" code:

$(document).on("change", '[id$=ddlPayToIndividual]', function () {
    var $individualSel = $('[id$="ddlPayToIndividual"]').val();
    if ($individualSel == "Damage Payment" {
        alert("you selected Damage Payment");
    }
});

But this not only doesn't work (I see no alert when selecting the "Damage Payment" selection), but prevents other, previously-working code from working. Is my assumption that the selected value can be accessed via "val()" wrong? Or...

Upvotes: 0

Views: 128

Answers (3)

Barmar
Barmar

Reputation: 782148

To access the target element of the event, use $(this).val(). $('[id$="ddlPayToIndividual"]').val() returns the value of the first element in the document that matches the selector, not the one that triggered the event.

BTW, instead of using the ID selector [id$=ddlPayToIndividual], you should give all these elements a common class, e.g. class="ddlPayToIndividual". Then you can use the selector .ddlPayToIndividual. E.g.

<select class="ddlPayToIndividual" name="ctl00$ctl24$g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33$ctl00$ddlPayToIndividua‌​l" id="ctl00_ctl24_g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33_ctl00_ddlPayToIndividual"‌​> 

Upvotes: 1

The problem was that I was getting "val" and the displayed value confused. As the dropdownlist/select is created like so:

DropDownList ddlPaymentToIndividual = new DropDownList();
ddlPaymentToIndividual.ID = "ddlPayToIndividual";
ddlPaymentToIndividual.Items.Add(new System.Web.UI.WebControls.ListItem("Select type", "0"));
ddlPaymentToIndividual.Items.Add(new System.Web.UI.WebControls.ListItem("Damage Payment", "1"));
. . .

...I had to change the jQuery to this:

$(document).on("change", '[id$=ddlPayToIndividual]', function () {
    var value = $(this).val();

    if (value == '1') {
        alert('you selected Damage Payment');
    }
    else {
        alert(value);
    }
});

Thanks to sushil's answer, I was able to see that.

Upvotes: 0

Sushil
Sushil

Reputation: 2835

Try using $(this).val() to get the value of the selected dropdown. also if you need to use the id selector, just use #ddlPayToIndividual

but if you need to use this on several dropdowns, then as @Barmar suggested, try giving all your dropdowns a class and use the class selector instead of the id

here's what i have done.

$(document).ready(function() {

    $(document).on("change", '#ddlPayToIndividual', function() {

        var value = $(this).val();

        if (value == 'Damage Payment') {
            alert('you selected Damage Payment');
        }
    });
});

notice the #ddlPayToIndividual instead of the [id$=ddlPayToIndividual] in the change event.

here's a working JSFIDDLE for the same.

Upvotes: 3

Related Questions