JQuery function only works within a function

后端 未结 1 926
一生所求
一生所求 2020-12-04 02:58

I have a page with a dropdown list and one of the options in ADD NEW. The function created for it works great.

$(\'#town_id\').on(\'change\', function(){
            


        
相关标签:
1条回答
  • 2020-12-04 03:48

    Yes there is a solution. You have to use delegation because the HTML element is created dynamically.

    Considering the .towns element the container of the select box and #town_id the select box the syntax looks like this:

    $('.towns').on('change', '#town_id', function(){
        if($(this).val() == "ADD_NEW"){
            console.log('Add New');
            $('#town_id').val('');
            $('#town_id').trigger('chosen:updated');
            $('#modal-1').modal('show');
        }
    });
    

    And yes, this will work for both static and dynamic select box.


    Direct and delegated events

    When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. [...]

    Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

    Read more

    0 讨论(0)
提交回复
热议问题