Jquery – Changing input name using JQUERY

domjquery

I'm trying to change all the input name based on the list index of <li> but it seems like it's not changing at all.

$('.test').click(function() {
for(var i=0;i<$("li.songs").length;i++)
{
  var ob = $("li.songs").eq(i).clone();
  ob.find('input').each(function()
  {
    this.name = this.name+i;
    alert(this.name); //just checking if does it change
  });      
}
});

Now, the alert displays the right name I want, BUT no changes on the name when I inspect the element AND try to submit the form and display all the POST values.

Example expected output before changing:

<li class="songs"><input type="text" name="song" /></li>
<li class="songs"><input type="text" name="song" /></li>
<li class="songs"><input type="text" name="song" /></li>

After changing:

<li class="songs"><input type="text" name="song1" /></li>
<li class="songs"><input type="text" name="song2" /></li>
<li class="songs"><input type="text" name="song3" /></li>

NOTE: I DO NOT WANT the input named song to be an ARRAY.

Best Answer

You are cloning the object, so the change is done to a copy rather than the original DOM node.

Don't use clone() and you'll be fine. Or do this:

$("li.songs input").each(function(i) {
  $(this).attr('name', $(this).attr('name') + i);
});