1. 程式人生 > >Layui 動態渲染select框

Layui 動態渲染select框

 描述: 選擇部門,出來對應部門下面的分組,HTML程式碼如下:

<form class="layui-form" name="myform" method="post" action="">
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">部門</label>
            <div class="layui-input-inline">
                <select class="seloption" lay-filter="departmentid" name="departmentid" id="departmentid">
                    <option value="1">部門1</option>
                    <option value="2">部門2</option>
                    <option value="3">部門3</option>
                </select>
            </div>
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-inline">
            <label class="layui-form-label">分組</label>
            <div class="layui-input-inline layui-form" lay-filter="group">
                <select class="seloption" name="groupid" id="groupid">
                </select>
            </div>
        </div>
    </div>
    <div class="layui-form-item" style="margin-left:15rem">
        <div class="layui-inline">
            <button class="layui-btn" lay-submit="" lay-filter="submitAdd">提交</button>
        </div>
    </div>
</form>

 js程式碼如下:

layui.use(['element', 'layer','form'], function () {
    var element = layui.element,
        form = layui.form,
        layer = layui.layer;
    form.on('select(departmentid)', function(data){
        console.log(data.value);
        $.ajax({
            type:'post',
            url:'index',
            data:{departmentid:data.value},
            dataType:'json',
            async:true,
            success:function(datas){ 
                if(datas == 9){
                    var option = '';
                    for(var i=0;i<datas.length;i++){ 
                        //迴圈獲取返回值,並組裝成html程式碼
                        option +="<option value='"+datas[i].groupid+"'>"+datas[i].groupname+"</option>";
                    }
                }else{
                   var option = '<option value="0">請選擇</option>';  //預設值
                }
                $("#groupid").html("");
                $("#groupid").append(option);
                form.render('select','group');
            },
        });
    });
}); 

好了,這次應該記住了吧,每次遇到這兒每次都要耽誤時間琢磨, 真的是好記性不如爛筆頭!