layui和jQuery根據資料庫給複選框設定預設被選中checked
阿新 • • 發佈:2019-01-03
設定複選框被選中
- 根據資料庫查詢的資料與input標籤的title的值對比,相同則頁面載入時預設被選中
- layui設定被選中後,必須要進行“更新渲染”後,複選框才會顯示被選中,否則只是checked改變,頁面複選框無變化
更新渲染
1. 頁面
<form id="form" class="layui-form" action="" method="post">
<table id="recordsTable">
<tr class="tr-h">
<td class="w2-10">公司型別</td>
<td colspan="6">
<div>
<c:set value="0" var="status" scope="page"/>
<input type="checkbox" name="unitTypy" title="企業(分公司/其他)" lay-skin="primary">
<input type ="checkbox" name="unitTypy" title="事業單位" lay-skin="primary">
<input type="checkbox" name="unitTypy" title="其他組織" lay-skin="primary">
</div>
</td>
</table>
</form>
2. script
<script>
layui.use([ 'layer' , 'form', 'element' ], function() {
var $ = layui.jquery,
layer = layui.layer,
form = layui.form,
element = layui.element;
/* 自適應頁面 */
resizeTheWindow();
/* 視窗變化監聽 */
window.onresize = function() {
resizeTheWindow();
}
$(document).ready(function(){
$.ajax({
type: "GET",
url: "${pageContext.request.contextPath}/***/***" ,
dataType: "json",
cache: false,
async: false,
success : function(data) {
//給公司型別賦值並設定預設選中
var unitType=[];
unitType=data.unittypy.split(",");
for(var j=0;j<unitType.length;j++){
var unitTypeCheckbox=$("input[name='unitTypy']");
for(var i=0;i<unitTypeCheckbox.length;i++){
if(unitTypeCheckbox[i].title==unitType[j]){
unitTypeCheckbox[i].value=unitType[j];
unitTypeCheckbox[i].checked=true;
}
}
form.render(); //更新渲染
}
},
complete : function(XMLHttpRequest, textStatus) {},
ifModified : false,
error : function() {}
});
});
/* 自適應頁面 */
function resizeTheWindow() {
var screenWidth = parseInt(document.documentElement.clientWidth * 0.6);
var surplusWidth = ((screenWidth - 210) > 754)?(screenWidth - 210):754;
document.getElementById('contentContainer').style.width = surplusWidth + 'px';
}
});
</script>
jQuery設定checked的方法
- 設定複選框的選中或取消
$("[name='checkbox']").attr("checked",'true');//全選
$("[name='checkbox']").removeAttr("checked");//取消全選
$("[name='checkbox']:even").attr("checked",'true');//選中所有奇數
- 設定某個被選中
$("#input").prop("checked",true);
$("[name='unittype']").prop("checked",true);
$("[name='checkbox1']").attr("checked",'true');
- 判斷複選框是否被選中
var isChecked = document.getElementById("share_all").checked; //js判斷checkbox的選中狀態
var isChecked = $("#checkbox_id").attr("checked")=="checked"; //jquery判斷checkbox的選中狀態