layui 二级联动

HTML 部分

<form onsubmit="return false;" action="__SELF__" data-auto="true" method="post"
      class='form-horizontal layui-form' style='padding-top:20px'>
    <input type="hidden" name="id" value="{:input('id')}"/>
    <div class="form-group">
        <label class="col-sm-2 control-label">期刊</label>
        <div class='col-sm-3'>
            <select name="magazine" placeholder="请选择期刊" lay-filter="magazine">
            <option value="">请检索关键词或选择</option>
            {volist name="$magazines" id="magazine"}
            <option value="{$magazine.id}">{$magazine.name}
            </option>
            {/volist}
            </select>
        </div>
        <div class="col-sm-3">
            <select name="publish" id="publish">
                <option value=""></option>
            </select>
        </div>
    </div>


    <div class="hr-line-dashed"></div>
    <div class="col-sm-8 col-sm-offset-2">
        <div class="layui-form-item text-center">
            <button class="layui-btn" type="submit">提交数据</button>
        </div>
    </div>
</form>

JS 部分

<script>
    layui.use('form', function(){
        var form = layui.form;
        form.on('select(magazine)', function(data){
            var areaId=data.elem.value;
            $.ajax({
                type: 'POST',
                url: "{:url('getPublish')}",
                data: {areaId:areaId},
                dataType:  'json',
                success:function(e){
                    console.log(e.data);
                    //empty() 方法从被选元素移除所有内容
                    $("select[name='publish']").empty();
                    var html = "<option value='0'>选择期数</option>";
                    $(e.data).each(function (v, k) {
                        html += "<option value='" + k.id + "'>" + k.title + "</option>";
                    });
                    //把遍历的数据放到select表里面
                    $("select[name='publish']").append(html);
                    //从新刷新了一下下拉框
                    form.render('select');      //重新渲染
                }
            });
        });

    });
</script>

 

posted @ 2018-07-03 17:54  猿飞侠  阅读(8352)  评论(0编辑  收藏  举报