15

I'm trying to create a cascade dropdown with all dynamic elements.

My Html:

 <select id="Sites" name="SelectedSiteId"><option value=""></option></select>
 <select id="Sectors" name="SelectedSectorId"><option value=""></option></select>

I have 2 functions to load elements using ajax, both working fine:

function GetSites() {
        $.ajax({
            url: '/Sites/GetSites',
            dataType: "json",
            type: "POST",
            error: function () {
                alert("An error ocurred.");
            },
            success: function (data) {
                var items = "";
                $.each(data, function (i, item) {
                    items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
                });
                $("#Sites").html(items);
            }
        });
    }

    function GetSectors(siteId) {
        $.ajax({
            url: '/Sites/GetSectors',
            data: { siteId: siteId },
            dataType: "json",
            type: "POST",
            error: function () {
                alert("An error ocurred.");
            },
            success: function (data) {
                var items = "";
                $.each(data, function (i, item) {
                    items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
                });
                $("#Sectors").html(items);
            }

        });
    }

I need to call GetSectors based on the Site selection. I have this:

$(document).ready(function () {                       
        $("#Sites").on("change", function (e) {
            var siteId = $("#Sites").val();
            GetSectors(siteId);                
        });

        GetSites();
    });

But it doesn't work. I'm using jquery 1.8.3.

Any Idea where is the problem?

Thank you!

estebane97
  • 1,138
  • 2
  • 7
  • 25

2 Answers2

52

Try Event Delegation:

$(document).on("change", "#Sites", function(){
    var siteId = this.value;
    GetSectors(siteId);  
});

The bubbling behavior of events allows us to do "event delegation" — binding handlers to high-level elements, and then detecting which low-level element initiated the event.

Event delegation has two main benefits. First, it allows us to bind fewer event handlers than we'd have to bind if we were listening to clicks on individual elements, which can be a big performance gain. Second, it allows us to bind to parent elements — such as an unordered list — and know that our event handlers will fire as expected even if the contents of that parent element change.

Taken from: http://jqfundamentals.com/chapter/events

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

Taken from: http://api.jquery.com/on/

Chase
  • 29,019
  • 1
  • 49
  • 48
  • Hi, Thanks for your answer but still not working. I was wondering if it is related to one of the scripts MVC4 add, like jquery.unobstrusive-ajax, jquery-validate or jquery.validate.unobstrusive but I dont think so. – estebane97 Jan 15 '13 at 21:34
  • yes, and if I just call the method GetSectors(1) it works fine – estebane97 Jan 15 '13 at 21:39
  • Can you add an `alert` or a `console.log` inside the change event to make sure that the event is firing and that the value is present...something like `alert(this.value);` inside the event should work fine. – Chase Jan 15 '13 at 21:41
  • already try and nothing happens, I'm looking in Firebug to see if I can find something wrong – estebane97 Jan 15 '13 at 21:46
  • Well looks like my browser was not working properly, I just restart the browser and works! thanks a lot! – estebane97 Jan 15 '13 at 22:02
  • @estebane97 might have something to do with your cache – happy Mar 17 '14 at 00:04
1

I had the same problem on binding change function for dynamically added content. I solved it using this. Hope it helps someone ^^

$(".select_class").live("change", function(){
   console.log("testing...");
});
Marci Banez
  • 115
  • 1
  • 9
  • Please don't use ".live". This is used to help in converting from older jQuery event methods and were replaced in Typescript 1.7 by "$().on" https://api.jquery.com/on/ – Cvassend Jun 27 '19 at 14:12