Reputation: 33
I have a php file that generates a json array and i write this json array into file results.json
$jsonData = file_get_contents("/json/results.json");
$jsonDataObject = json_decode($jsonData, true);
<script>
var jsonObj = '<?php echo $jsonData;?>';
alert(jsonObj); //Produces the following output
{"cisco":["Port1/1","Port1/2","Port1/3"],
"Juniper":["Port2/1","Port2/2"],
"Huawei":["Port3/1","Port3/2","Port3/3","Port3/4"]
}
I want to build two dropdowns from this array, the first dropdown should have the keys alone like cisco,juniper,huawei etc.....
I did this using the following code:
<?php
foreach($jsonDataObject as $key => $value)
{
?>
<option value="<?php echo $key; ?>"><?php echo $key ; ?>
</option>
<?php }
?>
I need to split the values of each key on ',' and assign them to another dropdown using jquery.Iam stuck in this for a long time and i know numerous questions similar to this have been asked.Believe me i have tried my best but iam still stuck,i do not want to use ajax to do this.I would like to do this using jquery on the change event of the first dropdown.
Any help on this is much appreciated.
Upvotes: 0
Views: 1003
Reputation: 3392
Give the selects an ID:
<select id="select1">
<option value="cisco">cisco</option>
<option value="Juniper">Juniper</option>
<option value="Huawei">Huawei</option>
</select>
<select id="select2">
</select>
Then you can use this code:
function updateSelect() {
var newKey = $("#select1").val();
$("#select2").empty();
if(newKey in jsonObj) {
var tmp = jsonObj[newKey];
for(i = 0; i < tmp.length; i++)
{
$("<option>")
.attr('value',tmp[i])
.html(tmp[i])
.appendTo('#select2');
}
}
}
$(document).ready(function() {
$("#select1").change(updateSelect);
updateSelect(); // For initial page load.
});
See fiddle
Upvotes: 0