user415772
user415772

Reputation: 431

Looping and setting name and id in jquery

I have created a method to dynamically add rows to a table . each table tow contains two text fields(collectionText and Link)

<tr>
<td>
  <input type="text" size="30" id="txtCollectionText" name="txtCollectionText" />
</td>
 <td>
 <input type="text" size="30" id="txtLink" name="txtLink" />
 </td>
</tr> 

the bellow is my script

   function addRow() {
            var row = $('#table tbody>tr:last').clone(true).insertAfter('#table tbody>tr:last');
            var index = $("#table tbody>tr").length;
            $("td:eq(0)", row).text(index);
            $("td:eq(1) input", row).attr("name", "txtCollectionText" + index).attr("id", "txtCollectionText" + index)
            $("td:eq(2) input", row).attr("name", "txtLink" + index).attr("id", "txtLink" + index)
        }

This will add the index to newly added inputs.but not to the existing ones . my requirement the indexes should start form zero . for example if i have 2 rows by default ,adding third row will give me collectiontext4 and link4 , but i want numbering for all my rows starting from 0 -4 ...any ideas ??

Upvotes: 1

Views: 1065

Answers (2)

scronide
scronide

Reputation: 12238

Based on your addRow() function and, therefore, the assumption that the table actually has 3 columns.

$(function() {
  reindexRows();
});
function addRow() {
  $("#table tbody>tr:last").clone(true).insertAfter("#table tbody>tr:last");
  reindexRows();
}
function reindexRows() {
  $("#table tbody>tr").each(function(index, ele) {
    $("td:eq(0)", ele).text(index);

    var collection_name = "txtCollectionText"+ index.toString();
    $("td:eq(1) input").attr({name: collection_name, id: collection_name });

    var link_name = "txtLink"+ index.toString();
    $("td:eq(2) input").attr({name: link_name, id: link_name });
  });
}

Upvotes: 0

Ian Henry
Ian Henry

Reputation: 22403

To bind the code to your document.ready event:

$(function() {
    $('#table tr').each(function(index, element)
    {
       var e = $(element);
       e.find('td:eq(0)').text(index);
       var first = 'txtCollectionText' + index.toString();
       var second = 'txtLink' + index.toString();
       e.find('td:eq(1) input').attr({name: first, id: first});
       e.find('td:eq(2) input').attr({name: second, id: second});
    });
}

If placed inside a script tag, this code will automatically execute as soon as the document is finished being constructed by the browser. That's what the $(function() {}) notation does -- it's shorthand for $(document).bind('ready', function() {}).

Upvotes: 1

Related Questions