Loop in JavaScript

2

I need to delete a line from a list. it changes an input items.

Example:

linha 01
linha 02
linha 03

If I delete line two now it stays:

linha 01
linha 03

But I did not want it that way, so I need it to change and leave it like this:

linha 01
linha 02

So I thought about doing this:

for (i = 1; i < quantidadeTR; i++) {
    $("input:text[name^='item']").val(i);           
}

quantityRT = is equal to the total of line taken by a function.

With the code above I have the result:

linha 02
linha 02

I have tried this way too but it gives the same error:

var count = 1;
    while ( count < quantidadeTR ) {        
        $("input:text[name^='item']").val(count);
    count++;
    };
    
asked by anonymous 02.10.2014 / 23:03

1 answer

6

When you do a query of these in jQuery and call the val method, you affect all the items that serve the query. This is why all the lines have the same text.

jQuery objects have a each function, which iterates over all the items retrieved by the query. For it you pass a function that receives two parameters: the first is the index of the current element and the second is the current element itself. What you want is something like:

$("input:text[name^='item']").each(function (index, elem) {
    $(elem).val(index);
});
    
02.10.2014 / 23:19