I have four <select>
element.
<div id="select-countries-container">
<select name="countryId" id="select-countries">
<option value="">Choose Country »</option>
<?php foreach($location->fetch(array('table' => 'countries')) as $country) { ?>
<option value="<?php echo $country['id']; ?>"><?php echo $country['name']; ?></option>
<?php } ?>
</select>
</div>
<div id="select-states-container"><select disabled="disabled"><option value="">Choose State »</option></select></div>
<div id="select-cities-container"><select disabled="disabled"><option value="">Choose City »</option></select></div>
<div id="select-areas-container"><select disabled="disabled"><option value="">Choose Area »</option></select></div>
the child element <select>
is replaced with the code received from Ajax, here is the Ajax 开发者_Python百科Code i am using.
$('#select-countries').change(function(){
var countryId = $(this).val();
if(countryId == ''){
$('#select-states-container').html(chooseState);
} else {
$.ajax({
type: 'POST',
url: 'process.php',
data: 'countryId='+countryId,
beforeSend: function() {
$('#select-states-container').html(loadingText);
},
success: function(states){
if(states == 'null') {
$('#select-states-container').html(emptyState);
} else {
$('#select-states-container').html(states);
}
}
});
}
});
and the data being retrieved from process.php is.
$select = '<select name="stateId" id="select-states">';
$select .= '<option value = "">Choose State »</option>';
foreach($states as $state) {
$select .= '<option value = "'.$state['id'].'">'.$state['name'].'</option>';
}
$select .= '</select>';
echo $select;
till here it works perfectly fine, the trouble starts when i select states from second <select>
i.e <select name="stateId" id="select-states">
retrieved from process.php, when i select the value from this it does not trigger the function it is bound to, i am not sure what is happening, here is what i tried to do.
$('#select-states').change(function(){
alert('Fire');
});
and this does not fire. what is wrong with my code?
thanks.
You should use .live().
From the documentation:
Description: Attach a handler to the event for all elements which match the current selector, now and in the future.
You need to use delegate()
to add the change handler to dynamically-created elements:
$("body").delegate("#select-states", "change", function(){
...
This is necessary because your existing code runs only once ( when the document is loaded, presumably) and binds the event handler only to the elements that exist at that time. Delegate will bind the event all existing elements, plus all elements that are created in the future. For more information, please see the jQuery delegate documentation.
If you wish, you can use bind()
instead. You would place the call to bind()
in the AJAX call's success function to attach the event handler to the element after it is created.
EDIT
For a good analysis on the differences between delegate()
and live()
, see jQuery: live() vs delegate()
精彩评论