2013-03-13 25 views
1

document.friendform1.friends [i] .checked在複選框數組中只有一個元素時不起作用。如果在複選框陣列多個元素比它做工精細document.friendform1.friends [i] .check在checkbox數組中只有一個元素時不工作

我的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 
} ?> 

和JavaScript代碼是:

function addalfriend() 
{ 
    var str=''; 
    var str1=''; 

    var len=document.friendform1.friends.length; 
    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 
     { 
      str=str+","+document.friendform1.friends[i].value; 
      str1=str1+","+document.friendform1.frnd[i].value; 
     } 
     } 
    } 
     document.getElementById('invite_1').value=str; 
     if(str!='' && str1!=''){ 
      document.getElementById('invited').style.display="block"; 
     } 
     else{ 
      document.getElementById('invited').style.display="none"; 
     } 
     document.getElementById('invited').value = str1; 
     document.getElementById("low-high-div").style.display="none"; 
     document.getElementById("events-input-bg2").value=""; 
     document.getElementById("events-input-bg3").value=""; 
     closemessage1(); 
     return false; 

} 

所以請有人讓我知道我的錯。

感謝

+0

什麼喲你想實現?你什麼時候調用這個函數addalfriend – 2013-03-13 07:28:13

+0

我想添加勾選複選框的值隱藏字段。和我打電話addalfriend點擊一個按鈕 – 2013-03-13 07:30:43

+0

哪個按鈕?並且在哪個隱藏字段中添加選中的複選框值? – 2013-03-13 07:36:00

回答

2

當有返回一個項目的回報則數組不重新調整元素的對象,所以你需要以不同的方式訪問它,然後 作爲

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; 
    } 
    } 
. 
. 
. 

} 
+0

感謝Rab,但它不進入循環,如果只有一個元素,所以我應該保持其他部分out of for循環? – 2013-03-13 07:49:06

+0

是的,這就是我想說的 – Rab 2013-03-13 07:49:42

+0

是的nawaz它爲我工作真的很感謝你 – 2013-03-13 07:52:16

相關問題