I have two select dropdowns where the options of the 2nd select box needs to be changed according to the 1st select. The form is
<form action="" method="post" >
<div style="padding-bottom:6px;">
<select id="portfolios" name="portfolio" style="width: 200px; height:25px;">
<option selected="selected" value="default">Select Portfolio</option>
{% for portfolio in portfolios %}
<option get-groups="{{ path('v2_pm_patents_getgroups') }}" value={{ portfolio.id }}>{{ portfolio.portfolioName }}</option>
{% endfor %}
</select>
<span>OR</span>
<a class="modalbox1" href="#inline1">[Add New Portfolio]</a>
</div>
<div style="padding-bottom:6px; display:none;" id="groups">
<select id="portfolio-groups" name="portfolio-groups" style="width:200px; height:25px;">
<option selected="selected" value="default">Select Portfolio Group</option>
</select>
<span> OR</span>
<a class="modalbox2" href="#inline2">[Add New Group]</a>
</div>
</form>
Initially the 2nd dropdown is hidden when I select an option from the 1st select it becomes visible.
The JQuery I wrote is
<script>
$(document).ready(function(){
$('#portfolios').change(function() {
$('#groups').show();
var id = $("#portfolios").val();
var url = $('option:selected', this).attr("get-groups");
var data = {PID:id};
$.getJSON(url, data, function(result) {
var options = $("#portfolio-groups");
$.each(result, function(item) {
options.append($("<option />").val(item.id).text(item.name));
});
});
});
});
</script>
My Controller method which I call is
public function getgroupsAction(Request $request){
if ($request->isXmlHttpRequest()) {
$id = $request->get("PID");
$em = $this->getDoctrine()->getEntityManager();
$portfolio_groups = $em->getRepository('MunichInnovationGroupPatentBundle:PmPatentgroups')
->getpatentgroups($id);
echo json_encode($portfolio_groups);
return new Response();
}
}
I get the correct groups from my query and in JSon Object. The Object in response looks like
[{"id":"09c0d4b2-ac25-11e1-96a5-9787dec335c2","name":"Group 2","description":"No Description Provided for this Group","order":500000,"is_deleted":false}]
In my JQuery I append options to select box but the problem is it appends the options but with empty value atribute and no text. So neither the text nor the value attribute is visible just empty options are added.
What I am doing wrong? and How can I clear the select box before appending options?
Thanks in advance
It looks like you are getting your JSON response wrapped inside an array. Try accessing your elements inside
$.eachlike thisitem[0].nameanditem[0].idThen you’d need to account for getting multiple objects and loop over the item array