tags:

views:

43

answers:

2

Hi,

I'm working on a script which will get a JSON array of id's. Based on the results, I then loop over all the checkboxes on the page and check the boxes where the id exists in the JSON array.

The checkboxes are named like so name="name[id]" id="name[id]"

How do I loop the checkboxes and determine if the id (between [ and ] ) exists in the JSON array?

+1  A: 

It isn't valid to have [ and ] in an HTML4 ID attribute.

That said, you could do a .filter() to check each item for the ID in the array:

var array; //holds the Array from the JSON

$(':checkbox').filter(function() {
    var id = this.id.slice( this.id.indexOf('[') + 1, -1 );
    return $.inArray( id, array ) > -1;
})
  .attr('checked','checked');
patrick dw
Will this work if the item being returned is a JSON array?
@user - As long as the JSON is valid and is properly parsed after it is received, then it will be just another javascript Array, so yes, it should work the same. :o)
patrick dw
+1  A: 

Patrick is correct, it's not valid to have [ and ] in an attribute. Assuming your HTML looks something like this:

<input type="checkbox" name="name1" /><br/>
<input type="checkbox" name="name2" /><br/>
<input type="checkbox" name="name3" /><br/>
<input type="checkbox" name="name4" /><br/>

You could use the Attribute Ends With Selector:

var ids = new Array();
ids[0] = 1;
ids[1] = 3;

$.each(ids, function(index, value) {
    $("input[name$='name" + value + "']").attr("checked", "checked");
});
MrDustpan