拆分逗号分隔值并与复选框值匹配,并选中该复选框及其父复选框

时间:2016-01-04 05:16:41

标签: javascript jquery

我的变量中有逗号分隔值存储,我将使用此逗号分隔值并与我的复选框值匹配,并使用这些匹配复选框值,我将检查该复选框及其父复选框。

我想在document.ready上执行此操作。



 $(document).ready(function () {
     var id="1,2"; //here id can contain value either 1,2 or 3,4
     //Now i want to split id variable value by comma and want to find all checkbox in Checkboxprocess div only and if any checkbox value match with checkbox then i want to
     //check that checkbox along with its parent checkbox.
     //For Eg if Id contains 1,2 then i want to check checkbox chkchild1 and chkchild2 and its parent chkParent1
   });

<div id="Checkboxprocess">
<div id="section1">
<input type="checkbox" id="chkParent1" runat="server" value="Check All" />
---------Parent of section 1----
    <li>
        <input type="checkbox" id="abc" runat="server" value="1" />
    </li>
    <li>
        <input type="checkbox" id="pqr" runat="server" value="2" />
    </li>                                
</div>
<br>
<br>

<div id="section2">
  <input type="checkbox" id="chkParent2" runat="server" value="Check All" />
  ---------Parent of section 2----
   
    <li>
        <input type="checkbox" id="lmn" runat="server" value="3" />
    </li>
    <li>
        <input type="checkbox" id="xyz" runat="server" value="4" />
    </li>                                
</div>
</div>
&#13;
&#13;
&#13;

这是我的小提琴链接:Fiddle

1 个答案:

答案 0 :(得分:1)

$(document).ready(function () {
var id = "1,2"; //here id can contain value either 1,2 or 3,4 //Now i want to split id variable value by comma and want to find all checkbox in Checkboxprocess div only and if any checkbox value match with checkbox then i want to //check that checkbox along with its parent checkbox. //For Eg if Id contains 1,2 then i want to check checkbox chkchild1 and chkchild2 and its parent chkParent1

/*Get All the checkbox. This includes parent checkboxes too*/
var allCheckboxes = $('#Checkboxprocess input:checked');

/*loop through checkboxes*/
$.each(allCheckboxes, function () {
    /*get the value of check box. Please note that this will also include the value of parent checkbox too but as the 'id' variable will only contain values of child checkboxes, the $.inArray(checkBoxVal,id) values always return '-1' in case of parent checkbox value. */
    /*Getting the value of each checkbox and $.inArray(checkBoxVal,id)
  checks if checkbox value present in id variable or not */
    var checkBoxVal = $(this).val();
    if ($.inArray(checkBoxVal, id) > -1) {
        /*Get parent checkbox*/
        var parentChechBox = $(this).closest('div').find(':checkbox:first');
        $(parentChechBox).prop('checked', 'checked');
    }
});});