tags:

views:

94

answers:

2

Here is my checkbox group

<input type="checkbox" name="checkGroup" id="all" value="0" >All 
<input type="checkbox" name="checkGroup" id="one" value="1">One 
<input type="checkbox" name="checkGroup" id="two" value="2">Two 
<input type="checkbox" name="checkGroup" id="three" value="3">three 

how to get array of checkbox by name "checkGroup" and then base on value set it checked / uncheck.

e.g. In edit mode i am getting string 012 from database then i need to set checked as All, One amd Two.

Please help thanks

+1  A: 
// Help us with finding values in arrays
Array.prototype.has=function(v){
  for (i=0; i<this.length; i++) {
    if (this[i]==v) return true;
  }
  return false;
} 

// Define our values
var myVals = [0,1,2];

// Check/Uncheck Accordingly
$(":checkbox[name='checkGroup']").each(function(){
  if (myVals.has($(this).val())) {
    $(this).attr("checked","checked");
  } else {
    $(this).removeAttr("checked");
  }
});
Jonathan Sampson
+1  A: 

If you go for this approach, of returning a string of numbers not separated by any character (like "012"), you can only handle without problems up to 10 elements (0-9):

function checkItems(str) {
  var checkboxes = $("input:checkbox[name='checkGroup']");
  checkboxes.attr('checked', false); // uncheck all boxes first
  checkboxes.each(function () {
    if (str.indexOf(this.value) >=0) {
      this.checked = true;
    }
  });
}

checkItems('012'); // checks all, one, and two

Check an example here.

CMS
What about something with the value 12 that isn't in 0, 1, or 2 but appears to be since 012 resembles 0 12?
Jonathan Sampson
With `'12'` it will check the "one" and "two" boxes (which I think that is the desired behavior by the OP)
CMS
ya its working thanksJonathan
Yashwant Chavan
Yashwant, if you don't anticipate having a checkbox with a value of "12" (twelve), this solution should work. But keep the future in mind.
Jonathan Sampson