Reputation: 1923
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: </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>
Upvotes: 0
Views: 85
Reputation: 570
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);
}
});
});
});
Upvotes: 1
Reputation: 23836
Consider this following addition:
$('body').on("change", "#state", function () {
^^^^^^^^
Upvotes: 0