jquery接收后台数组或集合回显复选框

  公司使用的框架比较旧,没有使用el等表达式。如果后台传递的是数组,需要把数组转为以逗号分隔的字符串。

<%
String context = request.getContextPath();
String valArr = (String)request.getAttribute("valArr"); //获取传递数组,已经转换成逗号分隔字符串
%>
var boxArr = $('input[type=checkbox]');//获取所有类型为checkbox标签
var result = '<%=valArr%>';//获取上面的字符串

var resultArr = result.split(",");//以逗号分隔为数组
$.each(resultArr,function(index,val){
    boxArr.each(function(){
        if($(this).val()==val.trim()){
            $(this).attr("checked",true);//选中
        }
    });        
});

Html代码

<div align="center">
      <input type="checkbox" value="1">西瓜
      <input type="checkbox" value="2">芒果
      <input type="checkbox" value="3"><input type="checkbox" value="4">菠萝
      <input type="checkbox" value="5">草莓
      <input type="checkbox" value="6">火龙果
 </div>
原文地址:https://www.cnblogs.com/nmnm/p/7666004.html