javascript select all checkboxes in a table

天大地大妈咪最大 提交于 2019-11-27 19:31:17
function checkAll(bx) {
  var cbs = document.getElementsByTagName('input');
  for(var i=0; i < cbs.length; i++) {
    if(cbs[i].type == 'checkbox') {
      cbs[i].checked = bx.checked;
    }
  }
}

Have that function be called from the onclick attribute of your checkbox to check all

<input type="checkbox" onclick="checkAll(this)">

Edit I misread your question a little, i see you have attempted it in your code. the getElementsByTagName has to be plural which you may have typo'd there and has to be a tag as specified by the answer above

Edit: Passing the master checkbox as a parameter would allow for toggling check/uncheck as suggested by vol7ron and has been modified in this answer appropriately.

The question asks for all checkboxes on the page so this would suffice.

However, providing control of which elements to look for checkboxes can be achieved in may ways, too many to go into detail but examples could be document.getElementById(id).getElementsByTagName if all checkboxes to be controlled are branched nodes from one element.
Otherwise, you can iterate through a further tag name retrieval / custom class name retrieval to name a few.

Example: http://jsfiddle.net/vol7ron/kMBcW/

function checkPage(bx){                   
   for (var tbls=document.getElementsByTagName("table"), i=tbls.length; i--; )
      for (var bxs=tbls[i].getElementsByTagName("input"), j=bxs.length; j--; )
         if (bxs[j].type=="checkbox")
            bxs[j].checked = bx.checked;
}

Have you tried jQuery? It's becoming javascript standart library for DOM manipulation (stackoverflow using in too).

With it you could do $(':checkbox').prop('checked', true); to check every checkbox on the page(but you probably wan't to check then only in table).

Well anyway start using jQuery, it will make your life easier and happier, and will save you a lot of time.

tag name is the bit that starts the html tag eg <input so the .getElementsByTagName ( "link" ) should be .getElementsByTagName ( "input" ) if you only want the name='link' then if(bxs.name =="link") { ... change the checked }

... or even simpler if you want to flip all checkboxes in the corresponding form:

function checkAll(bx){
    var form = bx.form;
    var ischecked = bx.checked;
    for (var i = 0; i < form.length; ++i) {
        if (form[i].type == 'checkbox') {
            form[i].checked = ischecked;
        }
    }
}

...

<input type="checkbox" onclick="checkAll(this)">
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!