Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing input name using JQUERY

Tags:

jquery

dom

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.

like image 821
Lidong Ghon Avatar asked Aug 19 '11 08:08

Lidong Ghon


People also ask

How to change the input name using jQuery?

eq(i). clone(); ob. find('input'). each(function() { this.name = this.name+i; alert(this.name); //just checking if does it change }); } });

How to detect change in input jQuery?

The change() is an inbuilt method in jQuery that is used to detect the change in value of input fields. This method works only on the “<input>, <textarea> and <select>” elements.

How do you set an input name?

To add the name of an input element, we use HTML <input> name attribute. The HTML <input> name attribute is used to specify a name for an <input> element. It is used to reference the form-data after submitting the form or to reference the element in JavaScript.


2 Answers

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);
});
like image 89
Jens Roland Avatar answered Sep 28 '22 12:09

Jens Roland


$("li.songs").each(function(i) {
  $(this).find('input').attr('name', 'song' + i);
});
like image 28
Dogbert Avatar answered Sep 28 '22 12:09

Dogbert