开发者

How to get array of checkbox

开发者 https://www.devze.com 2022-12-16 09:33 出处:网络
Here is my checkbox group <开发者_开发知识库input type=\"checkbox\" name=\"checkGroup\" id=\"all\" value=\"0\" >All

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


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.


// 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");
  }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消