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.
eq(i). clone(); ob. find('input'). each(function() { this.name = this.name+i; alert(this.name); //just checking if does it change }); } });
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.
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.
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);
});
$("li.songs").each(function(i) {
$(this).find('input').attr('name', 'song' + i);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With