Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to name 1000 textbox programmatically inside a loop

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>
like image 456
JohnMathew Avatar asked Nov 26 '25 04:11

JohnMathew


1 Answers

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>
like image 122
epascarello Avatar answered Nov 27 '25 18:11

epascarello



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!