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

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

What about something with the value 12 that isn't in 0, 1, or 2 but appears to be since 012 resembles 0 12?
With '12' it will check the "one" and "two" boxes (which I think that is the desired behavior by the OP)
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.
1
// 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");
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.