0

How can I iterate over the following HTML using Javascript in order to add a 1 to all the name fields. For example, "account" would become "account1", etc. I cloned this row from a table, and would like to be able to distinguish between the fields of the two.

<td>
    <select name="account">…</select>
</td>
<td>
    <span>
        "$ "<input type="text" name="debit" placeholder="100">
    </span>
</td>
<td>
    <span>
        "$ "<input type="text" name="credit" placeholder="100">
    </span>
</td>
<td>
    <input type="text" name="reference">
</td>
<td>
    <input type="text" name="notes">
</td>
<td>
    <select name="account">...</select>
</td>

2 Answers 2

1

One way you can do this is use querySelectorAll to get your elements inside your table, then use a loop and change their names:

var inputs = document.querySelectorAll("#myTable [name]")
inputs.forEach(function(input){
    input.name += + "1";
});

JSFiddle Demo

Sign up to request clarification or add additional context in comments.

4 Comments

This worked great, except for an item <td><select name="account">...</select></td>. I probably should have included that one in my original question. (Also, I am not selecting all elements in the table, only of a certain row which has `id=entryLine1').
Switched the #myTable input to #myTable [name]. Works great!
@cpage Yes sorry about that, re-read the question and changed my answer slightly. I didn't notice your select element initially.
And I am using, input.name = input.name.replace(/\d+/g, '') + row_count to prevent "account2" from being "account12".
0

var all =document.getElementsByTagName("*"); for (var i=0, max=all.length; i < max; i++){ if(all[i].name){ all[i].name+=1; } }

Try this.* will give you all elements in the page.

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.