Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

drop down list click event - jQuery

Tags:

jquery

I think this will be a really easy one for anyone that is decent with jQuery, but I've got dynamically generated dropdownlists on my page, and I've set up a click event on the class, which, as expected fires a click event for all of them. The ID of the select is dynamically generated, so I can't use that as the selector. I just want to fire the event for the select that is actually changed.

I need to use the id of the selected value in the function - anyone know how this is done?

Code I have so far:

$(document).ready(function () {
    $(".boxItem").change(function () {
        var str = $(this).attr('id');
        var num = $(this).val();
        alert(num);
        var url = "/Search/GetBoxChangeInfo";
        var vmData = { json : @Html.Raw(Json.Encode(Model)),
                        id : str,
                        boxNo : num };
        $.post(url, vmData, function (data) {
            $("#column-1").html(data);
        });
    });
});

Many thanks

like image 713
e-on Avatar asked May 02 '26 12:05

e-on


2 Answers

If it's dynamic you'll need to delegate:

$(document).on('change', '.boxItem', function () {
    var str = this.id;
    var num = this.value;
    ......

this will refer to the select with the class .boxitem that was changed, and getting the ID and value should work as expected, also replace document with closest non dynamic parent!

like image 58
adeneo Avatar answered May 05 '26 04:05

adeneo


$(".boxItem").on("change", function () {

    // to get the value and id of selected option
    var str = $('option:selected', this).attr('id');
    var value = $('option:selected', this).attr('value');

    // or to get value and id of select box use
    var str = this.id; 
    var value = this.value;
    ......
});

If you select is live i.e created after DOM ready then you should try

 $("body").on("change", ".boxItem", function () {

    // to get the value and id of selected option
    var str = $('option:selected', this).attr('id');
    var value = $('option:selected', this).attr('value');

    // or to get value and id of select box use
    var str = this.id; 
    var value = this.value;
    ......
});
like image 28
thecodeparadox Avatar answered May 05 '26 03:05

thecodeparadox