I am currently implementing a triple dependent drop-down menu (think country->state->city) that is populated with AJAX requests.
Here is the code snippet of my drop-down structure:
//create a drop down of available accounts
echo 'Available Accounts: ';
echo '<select name="dropAccounts" class="dropAccounts">';
//if there is at least one account available
if (count($accsAvailable) > 0) {
echo '<option value="0">---Select an account---</option>'; //default option
foreach ($accsAvailable as $account) {
//populate from API
echo '<option value=' . $account->getId(). '>' . $account->getName() . '</option>';
}
} else {
echo '<option value="0">---No accounts available---</option>'; //else if no accounts exist
}
echo '</select>';
//for available webproperties
echo '<br> Available Webproperties: ';
echo '<select name="dropProperties" class="dropProperties">';
echo '<option selected="selected">---Select a webproperty---</option>';
echo '</select>';
//for available profiles
echo '<br> Available Profiles: ';
echo '<select name="dropProfiles" class="dropProfiles">';
echo '<option selected="selected">---Select a profile---</option>';
echo '</select>';
The important variables are dropAccounts
(country), dropProperties
(state), and dropProfiles
(city). The first drop-down is populated by an API call, and from there, an AJAX request grabs the value from it on an onchange
event as such:
<script type="text/javascript">
$(document).ready(function()
{
$(".dropAccounts").change(function()
{
var accountID = $(this).val(); //gets the account ID from drop-down value
$.ajax
({
type: "POST",
url: "propertyID.php",
data: {
'accountID' : accountID
},
cache: false,
success: function(html)
{
$(".dropProperties").html(html);
}
});
});
});
</script>
then propertyID.php then populates dropProperties
as such (assume I am grabbing the values from a database):
if($_POST['accountID'])
{
if ($accountID != "0") {
foreach ($webItem as $item) {
echo '<option value=' . $item->getId() . '>' . $item->getName() . '</option>';
}
}
}
else {
echo '<option value="0">---Select a webproperty---</option>';
}
I have similarly set up the third drop-down menu (dropProfiles
) to populate in the exact same way, assuming when the second drop-down menu repopulates that it triggers the javascript onchange
event. However, when I get the second drop-down to repopulate, it doesn't execute the javascript for the third drop-down.
Here is the javascript onchange function that should trigger the PHP script to populate dropProfiles
:
<script type="text/javascript">
$(document).ready(function()
{
$(".dropProperties").change(function()
{
var id = $(this).val(); //gets the profile ID from drop-down value
$.ajax
({
type: "POST",
url: "profileID.php",
data: {
'id' : id
},
cache: false,
success: function(html)
{
$(".dropProfiles").html(html);
}
});
});
});
</script>
Is there a workaround to this? Am I approaching this the wrong way?