开发者

Check/Uncheck all checkboxes with Javascript in a PHP array with keys

I have the following code:

<a href="javascript:setCheckboxes3(1);" class="chkmenu">Check All</a> |
<a href="javascript:setCheckboxes3(0);" class="chkmenu">Uncheck All</a> |
<a href="javascript:setCheckboxes3(2);" class="chkmenu">Invert Selection</a><br />开发者_如何学JAVA
<table>
<tr>
<td><input type="checkbox" name="names[8]" value="yes" />Paul</td>
<td><input type="checkbox" name="names[11]" value="yes" />Bob</td>
<td><input type="checkbox" name="names[44]" value="yes" />Tom</td>
</tr>
</table>

And the following script:

function setCheckboxes3(act)
  {
  elts = document.getElementsByName("names[]");
  var elts_cnt  = (typeof(elts.length) != 'undefined') ? elts.length : 0;
  if (elts_cnt)
    {
    for (var i = 0; i < elts_cnt; i++)
      {
      elts[i].checked = (act == 1 || act == 0) ? act : (elts[i].checked ? 0 : 1);
      }
    }
  }

The script is working with other arrays without keys, but I can't get it to work with this array which has keys.

Thanks in advance


You can use getElementsByClassName:

<script type="text/javascript" language="javascript">  
function setCheckboxes3(act) {
  var e = document.getElementsByClassName('names');
  var elts_cnt  = (typeof(e.length) != 'undefined') ? e.length : 0;
  if (!elts_cnt) {
    return;
  }
  for (var i = 0; i < elts_cnt; i++) {
    e[i].checked = (act == 1 || act == 0) ? act : (e[i].checked ? 0 : 1);
  }
}
</script> 

<a href="javascript:setCheckboxes3(1);" class="chkmenu">Check All</a> |
<a href="javascript:setCheckboxes3(0);" class="chkmenu">Uncheck All</a> |
<a href="javascript:setCheckboxes3(2);" class="chkmenu">Invert Selection</a><br />
<input type="checkbox" name="names[8]" class="names" value="yes" />Paul
<input type="checkbox" name="names[11]" class="names" value="yes" />Bob
<input type="checkbox" name="names[44]" class="names" value="yes" />Tom

OR you can use: getElementsByTagName

<script type="text/javascript" language="javascript"> 
function setCheckboxes3(act) {
  var e = document.getElementsByTagName('input');
  var elts_cnt  = (typeof(e.length) != 'undefined') ? e.length : 0;
  if (!elts_cnt) {
    return;
  }
  for (var i = 0; i < elts_cnt; i++) {
    if((e[i].type) == 'checkbox') {
      e[i].checked = (act == 1 || act == 0) ? act : (e[i].checked ? 0 : 1);
    }
  }
}
</script> 

<a href="javascript:setCheckboxes3(1);" class="chkmenu">Check All</a> |
<a href="javascript:setCheckboxes3(0);" class="chkmenu">Uncheck All</a> |
<a href="javascript:setCheckboxes3(2);" class="chkmenu">Invert Selection</a><br />
<input type="checkbox" name="names[8]" value="yes" />Paul
<input type="checkbox" name="names[11]" value="yes" />Bob
<input type="checkbox" name="names[44]" value="yes" />Tom

Did you get a chance to try jQuery?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜