rasny92
(Saminiemi)
1
hi,
My database:
CATEGORIES
id | name
SUBCATEGORIES
id | cat_id | name
And I would like to show a drop-down list of subcategories depending on the selected categories, how to do it?
<?= $form->field($model, 'categories')->dropDownList(
ArrayHelper::map(Categories::find()->all(),'id','name'),
['prompt'=>'Select category']
) ?>
softark
(Softark)
2
rasny92
(Saminiemi)
3
OK, I used this module http://demos.krajee.com/widget-details/depdrop
And this is my code:
_form:
<?= $form->field($model, 'categories')->dropDownList($catList, ['id'=>'cat_name', 'prompt'=>'Select category']);?>
<?= $form->field($model, 'subcategories')->widget(DepDrop::classname(), [
'options'=>['id'=>'sub_name'],
'pluginOptions'=>[
'depends'=>['cat_name'],
'placeholder'=>'Select subcategory',
'url'=> Url::to(['ad/subcat'])
]
]); ?>
and controller:
public function actionSubcat() {
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$id = $parents[0];
$out=\backend\models\Subcategories:find()
->where(['cat_name'=>$id])
->select(['id','sub_name AS name'])->asArray()->all();
echo Json::encode(['output'=>$out, 'selected'=>'']);
return;
}
}
echo Json::encode(['output'=>'', 'selected'=>'']);
}
And it works fine, but I would like to show or hide DIV depending on the selected subcategory.
And this is my code:
<?php $this->registerJs(' $(\'select[id="sub_name"]\').change(function(){
if ($(\'option:selected\').val() == 3)
document.getElementById("table").style.display = "block";
else
document.getElementById("table").style.display = "none";
});', View::POS_READY);
?>
But it does not work, it takes the value from category dropdown list.
How do I get the value from the selected sub-category?
mdomba
(Maurizio Domba Cerin)
4
That’s probably because you are using a general selector $(\‘option:selected\’).val(),
[size=2]try with $(\’#sub_name option:selected\’).val()[/size]