What i would like to happen is when i select an item from the first selection box, the 2nd selection box populates from a parseJSON.
I have 2 selection boxes: #web and #cats
web: has (at the moment) 3 options - All Websites (value=0), Website 1 (value=1) and Website 2 (value=2)
When i select from #web i should only get the categories for that particular website, however in PHP i have already considered "All Websites" and it duplicates the categories into each web object, but i also added "All Websites" to the json array, so that if it is reselected the selection box will repopulate.
This is the PHP Function (To create the JSON):
function catWebMix($user) {
$categories = getCategories($user);
$webAll = array('ID'=>0, 'WebID'=>'All', 'WebName'=>'All Websites');
$webSites = getWebsites($user);
array_unshift($webSites,$webAll);
$output = array();
foreach ($webSites as $k => $v) {
$output[$k] = $v;
foreach ($categories as $key => $value) {
if ($value['WebID'] == '0') {
$value['WebID'] = $v['ID'];
$output[$k]['Category'][] = $value;
} else if ($value['WebID'] == $v['ID']) {
$output[$k]['Category'][] = $value;
}
}
}
return array($output, json_encode($output));
exit;
}
I assign a variable to Smarty.
$webCats = catWebMix($user);
$smarty->assign('webCats', $webCats);
I then call it in JQuery. This is my failed attempt at creating the selection boxes change, im unsure on how to do it.
<script type="text/javascript">
var obj = $.parseJSON({$webCats[1]});
$('#web').on('change', function () {
var web = $(this).val();
$.each(obj, function () {
if (web == obj.ID) {
$.each(obj.Category, function (i,v) {
$('#cats').append("<option>"+v[3]+"</option>");
});
}
});
});
</script>
What i want it to do:
Remove all option attributes in #cats
Repopulate #cats with the data from the parseJson, based on the value from #web. #web value = (first) ID in JSON.
Place Category.ID as value for option, and Category.CatTitle as text
The json array looks like the following:
[
{
"ID": 0,
"WebID": "All",
"WebName": "All Websites",
"Category": [
{
"ID": "1",
"WebID": 0,
"CatTitle": "Category 1"
}
]
},
{
"ID": "1",
"WebID": "web1",
"WebName": "Website 1",
"Category": [
{
"ID": "1",
"WebID": "1",
"CatTitle": "Category 1"
},
{
"ID": "2",
"WebID": "1",
"CatTitle": "Category 2"
}
]
},
{
"ID": "2",
"WebID": "web2",
"WebName": "Website 2",
"Category": [
{
"ID": "1",
"WebID": "2",
"CatTitle": "Category 1"
}
]
}
]
Thanks for any help!