I am trying to populate the dropdown menu based on the selection of the first menu. using the code below it will just make the next dropdown to be empty
$(\".category_id\").change(function(){
$(\"#account_id > option\").remove();
$(\"#item_name_id > option\").remove();
var category_id={'category_id':$(this).val()};
$.ajax({
type: \"POST\",
url: 'getCategory1/',
dataType: \"json\",
data: category_id,
success: function(category_ids){
// category_ids = {"0":"Choose Account Name","2":"OfficeEquipment","3":"IT Equipment"}
$.each(category_ids,function(account_id,name){
var opt = $('<option />');
opt.val(account_id);
opt.text(name);
$(this).closest('td').next().find('select').append(opt);
});
}
});
});
The controller function I used:
public function actionGetCategory1(){
//Get all the sub categories a the main category
$cat_id = $_POST['category_id'];
$subCategory = Item::model()->getCategory1($cat_id);
echo(json_encode($subCategory));
}
The model function
public function getCategory1($cat_id){
$where = "WHERE category_id = $cat_id";
$select = "SELECT * FROM tbl_account $where";
$query = Yii::app()->db->createCommand($select)->queryAll();
$subCat = array();
$subCat[0] = "Choose Account Name";
if($query){
foreach($query as $row){
$subCat[$row['account_id']] = $row['account_name'];
}
return $subCat;
}
else{ return FALSE; }
}
The data to be loop in the $.each will be coming form the controller in json format. I used var_dump to display i.
string(189) "{"0":"Choose Account Name","2":"Information and Communication Technology Equipment","3":"Office Equipment","4":"Furniture and Fixtures","5":"Communication Equipment","6":"Other Equipments"}"
Should be something like this. You will need to use a better selector for getting your < select > tag.
$.each(category_ids,function(account_id,name){
var x = document.createElement('option');
x.setAttribute('value', account_id);
var y = document.createTextNode(name);
$(x).append(y);
$('#selectId').append(x)
});
EDIT After further discussion this looks like a better answer:
$(\".category_id\").change(function(){
var _this = this;
$(\"#account_id > option\").remove();
$(\"#item_name_id > option\").remove();
var category_id={'category_id':$(this).val()};
$.ajax({
type: \"POST\",
url: 'getCategory1/',
dataType: \"json\",
data: category_id,
success: function(category_ids){
// category_ids = {"0":"Choose Account Name","2":"OfficeEquipment","3":"IT Equipment"}
$.each(category_ids,function(account_id,name){
var opt = $('<option />');
opt.val(account_id);
opt.text(name);
$(_this).closest('td').next().find('select').append(opt);
});
}
});
});
This is something that trips up a lot of people. Here is a good quick read on "this" scope that should make this clearer to understand.http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments