Fill each value of an input with a string variable character

Asked

Viewed 52 times

0

I have a variable var string = 'TEST', and I intend to do something like:

<input type="text" id="um" value="T">
<input type="text" id="dois" value="E">
<input type="text" id="tres" value="S">
<input type="text" id="quatro" value="T">
<input type="text" id="cinco"value="E">

Using javascript, how is this possible?

3 answers

2

Create an array with ids of the target elements and the itere by the method Array.prototype.forEach() with the callback parameters v for value and i for the iterated element index.
With document.getElementById() passing by v as a parameter get the respective element and change its value by configuring the property value with the character i string.

let str = "TESTE";

['um', 'dois', 'tres', 'quatro', 'cinco'].forEach(function(v, i) {
  document.getElementById(v).value = (i < str.length) ? str[i] : "";
});
<input type="text" id="um"><br>
<input type="text" id="dois"><br>
<input type="text" id="tres"><br>
<input type="text" id="quatro"><br>
<input type="text" id="cinco"><br>

1

For the first input:

document.getElementById('um').value = string[0]

Second input:

document.getElementById('dois').value = string[1]

The index always starts with 0, the index 0 of the variable string in the case represents the letter "T" the index 1 represents the letter "e" and so quietly just do the same with the other fields, now you can use it inside a loop for to be shorter and more elegant and automated, if you have many inputs, I would use even in this amount.

1


Create a "div pai" to insert their inputs inside, then roll a for depending on the size of your string and then create an element input and use the method charAt() to take the character from that position and insert as value.
The final code will look like this:

var str = 'TESTE';
var div = document.getElementById('div-pai');

for(let i=0; i < str.length; i++) {
  var input = document.createElement("input");
  input.type = "text";
  input.id = "campo" + (i+1);
  input.value = str.charAt(i);
  div.appendChild(input);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.