简体   繁体   中英

Event binding using jQuery

I am trying to display city options based on State selected, where states are dynamically loaded according to selected country (country list is static). but the problem is my action page which receives the data from ajax is not receiving any value for state. This is my first try for event binding so please help.

 $(document).ready(function() { $('#country').change(function() { var value = $(this).val(); $.ajax({ url: "state_selector_db.php", method: "post", data: { "country": value }, success: function(result) { var obj = jQuery.parseJSON(result) $('div#state').html(obj.state); } }); }); $('body').on("change", function() { var value2 = $(this).val(); $.ajax({ url: "state_selector_db.php", method: "post", data: { "state": value2 }, success: function(res) { var obj2 = jQuery.parseJSON(res) $('div#city').html(obj2.city); } }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p><b>Country:&nbsp</b> </p> <select id="country"> <option value="na">Select</option> <option value="india">India</option> <option value="usa">USA</option> <option value="england">England</option> </select> <div id="state"></div> <div id="city"></div> 

You are on the right track but you will need a little change in event binding

to bind events to select element that you have populated after ajax use following. change event is of select.

$(document).ready(function () {
    $('body').on("change", "div#state select", function () {
        var value2 = $(this).val();
        $.ajax({
            url: "state_selector_db.php",
            method: "post",
            data: {
                "state": value2
            },
            success: function (res) {
                var obj2 = jQuery.parseJSON(res)
                $('div#city').html(obj2.city);
            }
        });
    });
});

Consider this following addition:

$('body').on("change", "#state", function () {
                       ^^^^^^^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM