3

I have 1000 text boxes. I'm trying to put name for all the 1000 text boxes programmatically in 5 minutes using string replace function or any method.

<html>
<form id="exp">
<input type="text" value="A1">
<input type="text" value="A2">
<input type="text" value="A3">
.
.
.
<input type="text" value="A1000">
</form>
</html>
var element = document.getElementById("exp");
var html = element.outerHTML;
html = html.replace("input type="text"","input type="text" name="name"");

I would like to show my expected result as 'var html' as follows

<html>
<form id="exp">
<input type="text" name="textbox1" value="A1">
<input type="text" name="textbox2" value="A2">
<input type="text" name="textbox3" value="A3">
.
.
.
<input type="text" name="textbox1000" value="A1000">
</form>
</html>
JohnMathew
  • 508
  • 1
  • 5
  • 21

2 Answers2

2

Matching html with a regular expression is a bad idea. Not sure why you would be doing it with a regular expression. Select the elements and set it in a loop.

document.querySelectorAll("#exp input").forEach(function (inp, index) {
  inp.name = 'textbox' + (index + 1);
  // inp.name = `textbox${index + 1}`;
})
<form id="exp">
  <input type="text" value="A1">
  <input type="text" value="A2">
  <input type="text" value="A3">
</form>
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

Use document.getElementsByTagName

    var inputs = document.getElementsByTagName("input");
    for(i=0; i<inputs.length; i++)
    inputs[i].name = "text" + (i + 1);
JohnMathew
  • 508
  • 1
  • 5
  • 21
  • What if there were less than 1000 inputs in the dom? Your code would break. Should loop over the length. – mbx-mbx Feb 04 '20 at 14:54