【发布时间】:2015-07-08 01:35:47
【问题描述】:
我正在尝试根据第一个菜单的选择来填充下拉菜单。使用下面的代码只会使下一个下拉列表为空
$(\".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);
});
}
});
});
我使用的控制器功能:
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));
}
模型函数
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; }
}
$.each 中要循环的数据将以 json 格式来自控制器。我使用 var_dump 来显示 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"}"
【问题讨论】:
-
您的选择器是否返回任何内容?你能包括你的html吗?甚至可能是一个jsfiddle。我认为您的选择器不正确。 $.each 中的 $(this) 不会是你想要的。
-
是的,如果我在 $.each 中使用 $(this),它会导致未定义,但如果我在 $.each 之外使用它,它会给出未定义的结果。
-
ajax 调用在哪里...是否在事件处理程序中
-
另一个下拉菜单的onchange事件触发
-
您是否尝试构建级联下拉菜单并希望在下一个选择框上堆叠选项?
标签: jquery dynamic drop-down-menu