1

I have a series of select fields that is created when I click the "Add" button. The select fields are created within an unordered list, and it goes a little like this:

<li><select name="fieldname1"></select><input type='button' name='delbtn1'></li>
<li><select name="fieldname2"></select><input type='button' name='delbtn2'></li>
<!--etc-->

As you can see, I've given a sequence in the names. This is to allow me to do server side scripting after the form is submitted.

I'm also allowing the user to delete the list item, but I would like to still retain the sequence naming after deletion. This would mean: if I delete "fieldname2" in between "1" to "3", I would like to resequence it to "1", and "2".

I've attempted to use the .each() method to go through each list item, but am unable to rename the name correctly.Don't really know what went wrong here.

JS Fiddle here: http://jsfiddle.net/kosherjellyfish/JsW3a/3/

kosherjellyfish
  • 361
  • 4
  • 16

2 Answers2

3

fiddle Demo

$("ul.criteriallist li .fieldname").each(function (index) {
    $(this).prop("name", "fieldname" + ++index);
});


or Better .prop()

fiddle Demo

$("ul.criteriallist li .fieldname").prop("name", function (index) {
    return "fieldname" + ++index;
});


fiddle Demo
$("ul.criteriallist li .fieldname").prop("name", function (index) {
    return "fieldname" + ++index;
});
$("ul.criteriallist li .deletebtn").prop("name", function (index) {
    return "delete" + ++index;
});


Problem with your code
$("ul.criteriallist li").each(function (index) {
    $(".fieldname").attr("name", "fieldname" + index + 1);
    // $(".fieldname") refers to all elements so it sets same value to all
   //index + 1 will concatenate string if index is 1 than it will result 11
  //you can use $(this).find(".fieldname")
});
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
1

There are two mistakes I just managed to find in your code,

  • You are re-assigning the name directly by using the class name. At that place you have to use $(this) to change the name of the targeting input element.

  • And you are concatenating the index values with out doing arithmetic calculations on it

Try this,

$("ul.criteriallist li").each(function (index) {
    $(this).find(".fieldname").attr("name", "fieldname" + (index + 1));
});

DEMO

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130