I have a form in that i have two dropdowns main category and sub category and both of them are populated by using ajax. the second dropdown(sub category) is disabled at first when the user selects main category dropdown then second dropdown is enabled and all the corresponding values are populated in it.(Like if fruits is selected then in subcategory dropdown will be populated with mango and apple) this all works fine till here.
Now the issue is when i go to the listing page and try to edit all the fields in the form is populated with previous values except sub category dropdown.
ex:- in edit main category dropdown will fetch fruits but sub category dropdown which should contain mango is empty.
please help me regarding this.
I'll add my ajax below to show how i am trying to achieve this.
To populate main category dropdown which is working
$.ajax
({
url: "listmaindropdown",
type: "GET",
dataType: "json",
success: function(loadmaindropdown)
{
var aaaa = $("#home_main_cat_dropdown_id");
$.each(loadmaindropdown, function(index,category)
{
$("<option>").val(category.m_id).text(category.main_category).appendTo(aaaa);
});
if(${product != null})
{
$('option[value="${product.home_main_category}"]').prop("selected","selected"); // its working here
}
},
})
For populating sub category dropdown
$("#home_main_cat_dropdown_id").change(function(value)
{
var main_category_values = this.value;
$.ajax
({
url: "listsubdropdown",
type: "GET",
data: "s_id=" main_category_values ,
dataType: "json",
success: function(loadsubdropdown)
{
var bbbb = $("#home_sub_cat_dropdown_id");
bbbb.find('option').remove();
$.each(loadsubdropdown, function(index,category)
{
$("<option>").val(category.m_id).text(category.sub_category).appendTo(bbbb);
});
if(${product != null})
{
// Here it's not working
$('#home_sub_cat_dropdown_id option[value="${product.home_sub_category}"]').prop("selected","selected");
}
},
});
});
CodePudding user response:
Your problem is that selecting an option by JavaScript does not fire the change event like documented in here.
You need to manually trigger the change event using .trigger("change")
.
In your case: $('option[value="${product.home_main_category}"]').prop("selected","selected").trigger("change");