二級聯動,第二級是多選框 multipleSelect
阿新 • • 發佈:2019-02-20
需要做個二級聯動的功能,第二級要求是多選,用的multiple-Select方法
以老師-學生為例,資料是從後臺傳到前臺頁面的一個list中帶list的JSONArray
引用(不要忘了引用圖片,要不輸入框右邊沒有三角)
<script src="js/multiple-select.js"></script>
<link rel="stylesheet" href="css/multiple-select.css" />
jsp頁面
js頁面<div> <select name="teacher" onchange="teacherChange()" > <option value="" selected="selected">未選擇</option> <c:if test="${teachers != null}"> <c:forEach items="${teachers}" var="teacher"> <option value="${teacher.id}">${teacher.name}</option> </c:forEach> </c:if> </select> </div> <div> <select id="student" multiple="multiple"></select> </div>
如果引用了之後頁面不美觀或者不協調,可以通過重新寫css的方法來修改。<script type="text/javascript"> var teachers = ${teachers}; $(function(){ $('#student').multipleSelect({ width : 120, allSelected: '全部', //option全部選了之後框裡顯示的內容 multiple : false, //是否在一行中顯示多個選項 selectAll: false, //是否顯示全選複選框 placeholder : '未選擇', //預設值 }); }); //改變teacher 切換student function teacherChange() { var teacherId = $("[name='teacher']").val(); var students = []; if (teacherId == null || teacherId == "") { $('#student').html(""); $('#student').multipleSelect("refresh"); //這步很重要 } else { $(teachers).each(function(index, teacher) { if (teacher['id'] == teacherId) { students = teacher['student']; return false; } }); var r = []; $(students).each(function(index, student) { r.push('<option value="'+ student['id'] +'">'+ student['name'] +'</option>'); }); $('#student').html(r.join('\n')); $('#student').multipleSelect("refresh"); //這步很重要 //因為是通過jquery手動更新option選項,所以要通過refresh方法來重新載入Multiple Select } } </script>