2010-12-06 111 views
0

我希望tds(textboxes)具有唯一的id's,以便我可以獲取在這些文本框中輸入的值。我如何給文本框獨一無二的id並獲取在這些文本框中輸入的值?jquery更改子元素ID

這裏是我的代碼:

<html> 
<head> 

<script type="text/javascript" src="jquery-1.3.2.min.js"></script> 

<style type="text/css"> 
    div{ 
     padding:4px; 
    } 
</style> 

</head> 

<body> 


<script type="text/javascript"> 

$(document).ready(
    function(){ 
    var counter = 2; 
     $('a.add').live('click', 
      function(){ 
       if(counter>5){ 
        alert("Only 5 textboxes allowed"); 
        return false; 
       } 
      $(this) 
       .closest('tr') 
       .clone() 
       .appendTo('table'); 
      $(this) 
       .text('Remove') 
       .removeClass('add') 
       .addClass('remove'); 
      counter++; 
      }); 
     $('a.remove').live('click', 
      function(){ 
       $(this) 
        .closest('tr') 
        .remove(); 
        counter--; 
      }); 
     $('input:text').each(
      function(){ 
       var thisName = $(this).attr('name'), 
        thisRrow = $(this) 
           .closest('tr') 
           .index(); 
       //$(this).attr('name', 'row' + thisRow + thisName); 
       // $(this).attr('id', 'row' + thisRow + thisName); 
      }); 
    $("#getButtonValue").click(function() { 
     var msg = ''; 
     for(i=1; i<counter; i++){ 
      msg += $('').val(); 
     } 
       alert(msg); 
     }); 
    }); 
</script> 
</head><body> 

<table> 
    <tr> 
     <th>Min Value</th> 
     <th>Max Value</th> 
    </tr> 
    <tr> 
     <td><input type="text" name="col1" id="col1" /></td> 
     <td><input type="text" name="col2" id="col2" /></td> 
     <td><a href="#" class="add">Add</a></td> 
    </tr> 
    <tr><input type='button' value='Get TextBox Value' id='getButtonValue'></tr> 
</table> 
</body> 
</html> 
+0

什麼是你的問題或問題? – 2010-12-06 10:10:17

+0

我想要獲得在這些文本框中輸入的值,並且文本框應該有唯一的ID。 – 2010-12-06 10:13:46

回答

1

使用,當您創建新行這...

 var newRow = 
      $(this) 
       .closest('tr') 
       .clone() 
       .appendTo('table'); 
     var i=1; 
     $('input',newRow).each(function(){ 
      $(this)[0].id="Col"+counter+"_"+(i++)} 
     ); 
0

爲了讓您的每一個<input>箱頁面獨特的IDS使用:

 var i=0; 
     $('input').each(function(){ 
      $(this)[0].id="TextBox"+(i++)} 
     ); 

這將給他們的TextBox0TextBox1等IDS ...

但是我注意到在你的HTML中發佈的所有輸入框已經有了唯一的ID。您是否計劃在運行時添加更多動態?

+0

這個id不是唯一的。對於一個tr是唯一的,但是它在下一個tr中再次重複。 – 2010-12-06 10:28:38

1

當你添加你要的ID分配給它的文本框,一個新行:

var i=0; 
$(this) 
    .closest('tr') 
    .clone() 
    .appendTo('table') 
    .children() 
    .each(function(){ 
     $(this)[i].id="textbox" + counter + (i++)} 

我選擇了一個id與第一號識別行和第二列。