2010-10-30 59 views
1

如果有人在這裏願意幫助我,我真的很感謝如何限制添加字段?

如何限制下列html代碼中的列的添加,比方說只有最多隻有5個?

<form action="<?php echo $action; ?>" method="post" enctype="multipart/form-data" id="friends" 
     <table width="100%" cellpadding="10" cellspacing="0" id="my_friends"> 
     <tr> 
      <th colspan="2" style="text-align: center;"><?php echo $text_enter_friend; ?></th> 
     </tr> 
     <tr> 
      <td class="left" width="30%"><span class="required">*</span> <?php echo $entry_friend; ?></td> 
      <td class="left"><input type="text" name="friend" value="<?php echo $friend; ?>" size="30" maxlength="45" /> 
      <?php if ($error_friend) { ?> 
      <span class="error"><?php echo $error_friend; ?></span> 
      <?php } ?></td> 
     </tr> 
     <?php if ($friends) { ?> 
     <?php foreach ($friends as $result) { ?> 
     <tr> 
      <td style="vertical-align: top;"><?php echo $entry_friend; ?></td> 
      <td style="vertical-align: top;"><input type="text" name="friends[]" value="<?php echo $result; ?>" size="30" maxlength="45" /></td> 
     </tr> 
     <?php } ?> 
     <?php } ?> 
     </table> 
     <table width="100%" cellpadding="10" cellspacing="0"> 
     <tr> 
      <td></td> 
      <td class="right"><a onclick="addFriend();" class="button"><span><?php echo $button_add_friend; ?></span></a><a onclick="removeFriend();" class="button"><span><?php echo $button_remove; ?></span></a></td> 
     </tr> 
     <tr> 
      <td colspan="2" class="center"> 
      <p><?php echo $text_message; ?></p> 
      <p><a onclick="$('#friends').submit();" class="button"><span><?php echo $button_submit; ?></span></a></p> 
      <p><?php echo $text_addresses; ?></p> 
      </td> 
     </tr> 
     </table> 
    </div> 
    </form> 

<script type="text/javascript"><!-- 
function addFriend() { 
    var tbl = document.getElementById('my_friends'); 
    var iteration = tbl.tBodies[0].rows.length; 
    newRow = tbl.tBodies[0].insertRow(-1); 
    var newCell = newRow.insertCell(0); 
    newCell.innerHTML = '<?php echo $entry_friend; ?>'; 
    var newCell1 = newRow.insertCell(1); 
    var el = document.createElement('input'); 
    el.type = 'text'; 
    el.name = 'friends[]'; 
    el.size = 30; 
    el.maxlength = 45; 
    newCell1.appendChild(el); 
// if (newCell > 2) tbl.addCell(newCell + 1); 
} 

function removeFriend() { 
    var tbl = document.getElementById('my_friends'); 
    var lastRow = tbl.rows.length; 
    if (lastRow > 2) tbl.deleteRow(lastRow - 1); 
} 
//--></script> 

在此先感謝

回答

0

表#my_friends默認有2行。所以你必須對行進行計數。

function addFriend() { 
var tbl = document.getElementById('my_friends'); 
var iteration = tbl.tBodies[0].rows.length; 
if(iteration>=7)return;//leave the function if already 5 rows have been added 

//rest of the function 
+0

謝謝,這項工作像一個魅力 – user485783 2010-10-31 02:47:51