Php document.friendform1.friends[i]。选中复选框数组中只有一个元素时不工作

Php document.friendform1.friends[i]。选中复选框数组中只有一个元素时不工作,php,javascript,html,Php,Javascript,Html,document.friendform1.friends[i]。当复选框数组中只有一个元素时,checked无效。如果复选框数组中有多个元素,则其工作正常 我的html和php代码是 $x=0; foreach($result as $row) { if($x==0) {?> <div class="invite-friends-con"> <?php }else{?> <div class=

document.friendform1.friends[i]。当复选框数组中只有一个元素时,checked无效。如果复选框数组中有多个元素,则其工作正常

我的html和php代码是

 $x=0;
foreach($result as $row)
{
    if($x==0)
    {?>
        <div class="invite-friends-con">
    <?php 
    }else{?>
        <div class="invite-friends-con" style="margin-left:70px;">
    <?php 
    }?>
    <div class="invite-friends-con-img">
       <img src="<?php echo base_url();?>Profile_images/<?php echo $row->vchPicture?>" width="48" height="39" align="absmiddle" />
    </div>
    <span><?php echo $row->vchFirstName?></span><input type="checkbox" name="friends[]"  style="margin-top:10px" value="<?php if($row->intFriendID==$this->session->userdata('user_id')){ echo $row->intMemberID;}else{ echo $row->intFriendID;}?>" id="friends"  />
    <input type="hidden" name="frnd[]" id="frnd" value="<?php echo $row->vchFirstName?>" />
    <?php if($x==1){$x=0;}else{$x++;}?>
<?php 
} ?>
$x=0;
foreach($结果为$行)
{
如果($x==0)
{?>
轮廓图像/“width=“48”height=“39”align=“absmiddle”/

当有一个项目返回时,则数组不返回元素对象,所以您需要以不同的方式访问它 作为

var len=document.friendform1.friends.length;
如果(len>1)

对于(i=0;i,您可以简单地像这样尝试:

var len=document.friendform1['friends[]'].length || 1;
for(i=0;i<len;i++)
{
  ...
    ...
   ...
}
...
...
...
var len=document.friendform1['friends[]]].length | 1;

对于(i=0;i您想实现什么?您何时调用此函数addalfriend?我正在尝试将复选框值添加到隐藏字段中。我在单击按钮时调用addalfriend哪个按钮?在哪个隐藏字段中添加复选框值?谢谢Rab,但如果只有一个元素,则不会进入循环我能不能让其他部分退出循环??
var len=document.friendform1.friends.length;
if(len>1)
for(i=0;i<len;i++)
{
  if(document.friendform1.friends[i].checked==true)
   {
     if(str=='')
     {
       str=document.friendform1.friends[i].value;
       str1=document.friendform1.frnd[i].value;
     }
.
.
.
}
else
{
  if(document.friendform1.friends.checked==true)
   {
     if(str=='')
     {
       str=document.friendform1.friends.value;
       str1=document.friendform1.frnd.value;
     }
   }
.
.
.

}
var len=document.friendform1['friends[]'].length || 1;
for(i=0;i<len;i++)
{
  ...
    ...
   ...
}
...
...
...