I am trying to update three linked Country -> Province -> City select box based on the previous select selection. The second part of my javascript is not working
$(document).ready(function() {
var $country = $('#person_country');
var $province = $('#person_province');
$country.change(function () {
// ... retrieve the corresponding form.
var $form = $(this).closest('form');
var data = {};
data[$country.attr('name')] = $country.val();
// Submit data via AJAX to the form's action path.
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: data,
success: function (html) {
// Replace current field ...
$('#person_province').replaceWith(
// ... with the returned one from the AJAX response.
$(html).find('#person_province')
);
}
});
});
$province.change(function () {
// ... retrieve the corresponding form.
var $form = $(this).closest('form');
// Simulate form data, but only include the selected value.
var data = {};
data[$province.attr('name')] = $province.val();
// Submit data via AJAX to the form's action path.
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: data,
success: function (html) {
$('#person_city').replaceWith(
// ... with the returned one from the AJAX response.
$(html).find('#person_city')
);
}
});
});
});
The second change function does not work. What am I doing wrong? Is there a way to call twice change and ajax functions?
The second change function does not work.
In this case you are adding an event to the 2nd select
(#person_province
) that was created during rendering, however, when you change the 1st select
, there's this code:
$('#person_province').replaceWith(
$(html).find('#person_province')
);
this deletes the existing select
and all existing events that are assigned to that select
.
One option is to use event delegation:
$(document).on("change", "#person_province", function...
the other option is to no use .replaceWith
but instead replace the contents (or inner HTML) with the new content, which will leave the select
intact along with the event(s) assigned.
Within the 1st select
callback, change the .replaceWith
to:
$('#person_province').html(
$(html).find("#person_province").html())
);