select2picker联动
PHP Code复制内容到剪贴板
- <?= $form->field($model, 'category_id')->dropDownListForPlugin(\common\modules\project2\models\ProjectCategory::getDropDownList('', 'category'), ['id' => 'firstSelect']) ?>
- <?= $form->field($model, 'subclass_id')->dropDownListForPlugin([], ['id' => 'secondSelect']) ?>
- <?php $this->beginBlock('js') ?>
- <script>
- // 获取点击事件
- var select1 = document.getElementById("firstSelect");
- select1.addEventListener('change', function () {
- // console.log(this.value)
- $.ajax({
- method: 'POST',
- url: '<?=\yii\helpers\Url::to(["/project2/category/index"])?>?parent_id=' + this.value,
- success: function (res) {
- const data = res.data;
- console.log(data.length)
- var opstr = "";
- if (data.length) {
- $.each(data, function (i, n) {
- opstr += " <option value=\"" + n.category_id + "\">" + n.title + "</option>";
- });
- } else {
- opstr = "<option value='0'>暂无小类</option>";
- }
- $('#secondSelect').html(opstr);
- $('#secondSelect').selectpicker('refresh');
- console.log(res)
- }
- });
- });
- //单一添加下拉改变事件
- select1.onmousedown = function () {//当按下鼠标按钮的时候
- this.sindex = this.selectedIndex;//把当前选中的值得索引赋给下拉选中的索引
- this.selectedIndex = -1;//把下拉选中的索引改变为-1,也就是没有!
- };
- select1.onmouseout = function () {//当鼠标移开的时候
- var index = id.selectedIndex;//获取下拉选中的索引
- if (index == -1) {//如果为-1,就是根本没有选
- this.selectedIndex = this.sindex;//就把下拉选中的索引改变成之前选中的值得索引,就默认选择的是之前选中的值
- }
- }
- // 初始化赋值
- initGetSecond();
- function initGetSecond() {
- //2:拿到选中项的索引:
- const index = select1.selectedIndex; // selectedIndex代表的是你所选中项的index
- //3:拿到选中项options的value:
- const select1Val = select1.options[index].value;
- //4:拿到选中项options的text:
- const select1Text = select1.options[index].text;
- if (select1Val) {
- $.ajax({
- method: 'POST',
- url: '<?=\yii\helpers\Url::to(["/project2/category/index"])?>?parent_id=' + select1Val,
- data: {
- "<?=Yii::$app->request->csrfParam?>": "<?=Yii::$app->request->getCsrfToken()?>"
- },
- success: function (res) {
- const data = res.data;
- var opstr = "<option value='0'>请选择</option>";
- if (data.length) {
- $.each(data, function (i, n) {
- opstr += " <option value=\"" + n.category_id + "\">" + n.title + "</option>";
- });
- }
- $('#secondSelect').html(opstr);
- $('#secondSelect').selectpicker('refresh');
- $('#secondSelect').selectpicker('val',<?=$model->subclass_id?>); //给它赋值
- }
- });
- }
- }
- </script>
- <?php $this->endBlock() ?>
下一篇 V2.0 - auth角色