Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming name attribute in <input> in different tables

Tags:

jquery

JSFiddle here: http://jsfiddle.net/pceh73g8/

In my script, I'm going to be loading tables that are going to be the same. The following is my example:

<table class="table">
<tr><td>First Name</td><td><input name="firstname" type="text"></td></tr>
<tr><td>Last Name</td><td><input name="lastname" type="text"></td></tr>
</table>

 <table class="table">
 <tr><td>First Name</td><td><input name="firstname" type="text"></td></tr>
 <tr><td>Last Name</td><td><input name="lastname" type="text"></td></tr>    
</table>

I wish to write a script to rename the names by index. Eventually, the output should be the following:

 <table class="table">
<tr><td>First Name</td><td><input name="firstname1" type="text"></td></tr>
<tr><td>Last Name</td><td><input name="lastname1" type="text"></td></tr>
</table>


 <table class="table">
 <tr><td>First Name</td><td><input name="firstname2" type="text"></td></tr>
 <tr><td>Last Name</td><td><input name="lastname2" type="text"></td></tr>    
</table>

I was trying to use .each() to go through each table, and get the index number of each table (to attach to the back of the input names).

I am unsure on how to select the within each of the tables. I seemed to be selecting all the :inputs instead. How do we select the "Children" of each table that are fields and rename them according to the index?

 $(".table").each(function(){ 
   //Get current index of the table 
   var i = $(this).index();

    $(":input").each(function(){ 
       var oldname = $(this).attr('name'); 
       $(this).attr('name',oldname+i);
    });

});
like image 872
kosherjellyfish Avatar asked Nov 30 '14 12:11

kosherjellyfish


1 Answers

That is because you are using a non-context specific $(':input') selector for each iteration, so all the input elements will just receive the index of the final <table> element. Use $(this) instead, and DOM transversal methods.

Also, .each() comes with a zero-based index i, so you actually don't have to redeclare it within the function :) however, note that since it is zero-based (i.e. starts from zero, and not one), you will have to add 1 to it (so you will have firstname1 instead of firstname0 for the first occurrence of an input element, for example).

$(".table").each(function(i){ 
    $(this).find(":input").each(function(){ 
        var oldname = $(this).attr('name'); 
        $(this).attr('name',oldname+(i+1));
    });    
});

See fixed fiddle here: http://jsfiddle.net/teddyrised/pceh73g8/4/


As per @dsfq's answer, you can also take advantage of using the .attr() method which accepts functions. I still learn something new everyday on here ;)

like image 171
Terry Avatar answered Oct 06 '22 18:10

Terry