Search code examples
arraysjsonjsfiddlecheckboxlist

Select checkboxes from JSON


I'm trying to get the selected check boxes from my JSON array but it only returns the checkbox with value="1"; What am I missing?

Here is my fiddle http://jsfiddle.net/geegirls3/acx1yLex/

  <div id="checkboxes">
      <input type="checkbox" name="qcol2" value="1" > Sarah
      <br />
      <input type="checkbox" name="qcol2" value="9" > Sundae
      <br />
      <input type="checkbox" name="qcol2" value="10" > Summer
      <br />
      <input type="checkbox" name="qcol2"  value="11" > GeeZee
      <br />
      <input type="checkbox" name="qcol2"  value="12" > Husband
      <br />
    </div>

$(document).ready(function() {
 var initValues = [{my_id: "10"}, {my_id: "11"}, {my_id: "12" }];
 var myjson = JSON.stringify(initValues);
 //alert(myjson);

 $('#checkboxes').find(':checkbox[name^="qcol2"]').each(function() {
   $(this).prop("checked", ($.inArray($(this).val(), myjson) != -1));
   //alert(myjson);
    });
 });

Solution

  • JSON.stringify converts the initValues map into a long string, not into an array that you can use inArray() with.

    If you want to select the checkboxes from a JSON string, you must first parse it, prepare an array with the id values, then you can use inArray to select the checkboxes.

    check this code:

       var myjson = JSON.stringify(initValues);
       var parsed = JSON.parse(myjson);
    
       var myarray = [];
       $.each(parsed,function(key, value) 
       {
         myarray.push(value["my_id"]);
       });
    
       $('#checkboxes').find(':checkbox[name^="qcol2"]').each(function() {
           $(this).prop("checked", ($.inArray($(this).val(), myarray) != -1));
           //alert(myjson);
       });