18

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.

1
  • actually that's a typical server-side task, you may generate correct name there. alternative - you can delete all this items and write back with JS (just I don't think that's a good practice) Commented Aug 19, 2011 at 8:21

2 Answers 2

39

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);
});
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.