dt888999 2013-08-05 10:07
浏览 45
已采纳

选中javascript中的所有复选框 - 使用不同值的数组复选框

JavaScript Code

function toggle(source) {

  console.log('here');
  checkboxes = document.getElementsByName('checkbox[]');

  for(var i=0, n=checkboxes.length;i<n;i++) {
       checkboxes[i].checked = source.checked;
    }
 }

PHP Code generating all checkboxes dynamically

    <td><input name="checkbox[<?php echo $row['id']?>]" type="checkbox" id="checkbox" value="<?php echo $row['id']; ?>"></td>

According to PHP code above All the name values are generated dynamically. Javascript code above is not able to select all the checkboxes

Please help!


After very long research finally found anser for my critical problem - Selecting & checking all the checkboxes with different name, value, id and same type.

function toggle (source) {
var checkboxes;
var len = document.frm1.elements.length;
var x = document.getElementById('all');

for(var i = 0 ; i< len;i++){

    if(document.frm1.elements[i].type == "checkbox")
        {

        checkboxes = document.frm1.elements[i];
        if(x.checked == true)
        {
            document.frm1.elements[i].checked = true;
        }
        else
        {
            document.frm1.elements[i].checked = false;
        }
           }

     /*if( isAllCheck == false ){
        document.frm1.elements[i].checked = "true";
        //alert( "it is false" );
    }else{ 
        document.frm1.elements[i].checked = "false";
        //alert( "it is true" );
    }
   isAllCheck = !isAllCheck; */


            }
     console.log(checkboxes);
     for(var i=0, n=checkboxes.length;i<n;i++) {

checkboxes[i].checked = source.checked;

       }

I hope this would help others...

  • 写回答

7条回答 默认 最新

  • dqpwdai095465 2013-08-05 10:23
    关注
    var inputs = document.getElementsByTagName("input");
    var checkboxes=[];
    for(var i = 0; i < inputs.length; i++) {
    if(inputs[i].type == "checkbox") {
        checkboxes.push( inputs[i] ); 
    }  
    }
    

    if you wish to check ALL of them, then you will have to add the line inputs[i].checked = true; inside the if condition

    Tip: don't assign same ID for the checkboxes!!!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程