bhttoan
bhttoan

Reputation: 2736

jQuery trigger change on loading a select via AJAX

I have a dropdown which loads another dropdown over AJAX - dropdown 1 shows a list of weeks and then dropdown 2 gets populated based on valid values from the week chosen in dropdown 1.

When the user then selects an item from dropdown 2, I am using a change event to display text to them on the screen.

All that works fine except that on the first load of dropdown 2 the change event does not trigger.

Code looks like this:

<select name="wb" id="wb" class="form-control">
<option value="2018-01-01">2018-01-01</option>
<option value="2018-01-08">2018-01-08</option>
<option value="2018-01-15">2018-01-15</option>
<option value="2018-01-22">2018-01-22</option>
<option value="2018-01-29">2018-01-29</option>
</select>

<select id="date" class="form-control" name="date"></select>

<div id="previous_disp"></div>

Code to get the days and populate dropdown 2:

function getDays() {
    var week = $("#wb").val();
    var uid = $("#uid").val();
    $.ajax({
        type : "GET",
        url: 'days.php?week='+week+'&uid='+uid,
        success : function(data){
            $('#date').html(data); 
        }
    })
}

days.php then produces a list of options like below which are populated into dropdown 2 (#date):

<option value='2018-01-15'>Mon 15/01/2018</option>
<option value='2018-01-18'>Thu 18/01/2018</option>
<option value='2018-01-19'>Fri 19/01/2018</option>

Final piece of code is then to display the div depending on what is in the #date dropdown:

$(function() {              
    $("#date").change(function () {
        var day = $(this).val();
        var uid = $("#uid").val();
        $.ajax({
            type : "GET",
            url: 'previousEntries.php?day='+day+'&uid='+uid,
            success : function(data){
                $('#previous_disp').html(data); 
            }
        })              
    });    
})

When using this, the first time the #date is loaded the change does not trigger hence #previous_disp never shows - if I then actually change the value of #date it works exactly as expected

Based on previous answers I found from extensive searching, I have tried some variations like:

$(function() {              
    $("#date").change(function () {
       ....
    }).change();    
})

and also

$(function() {              
    $("#date").change(function () {
       ....
    });    
})

$("#date").change;

but none of these work for me on that initial load - how can I get the above to work?

Upvotes: 0

Views: 3867

Answers (2)

Tony M
Tony M

Reputation: 741

Since the event is on a dynamically loaded element, I would use:

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

Upvotes: 0

Kishor Malakar
Kishor Malakar

Reputation: 77

You have to target the body perferrably since the second dropdown isn't available to the script at the time of page load.

$('body').on('change', '#dropdown2', function(){
    //some stuff
})

Upvotes: 2

Related Questions