I would like to read all values from a text field/text box individually and then write them to a table:
Example:
JavaScript
x
2
1
This is an example of a text I want to read out.
2
Output:
- This
- is
- an
- example
- of
- a
- text
- I
- want
- to
- read
- out
How can I use a loop to read the text field/textbox? That is, whenever a space comes the new subsequent value must be in a new line.
Advertisement
Answer
String:
JavaScript
1
13
13
1
var table = document.getElementById("table");
2
var phrase = "This is an example of a text I want to read out";
3
4
var words = phrase.split(" ");
5
for (var i = 0; i < words.length; i++) {
6
var tableCol =
7
`<tr>
8
<td>${i+1}:</td>
9
<td>${words[i].replace(/[.,!?]/g," ")}<td>
10
</tr>`;
11
12
document.querySelector('table tbody').innerHTML += tableCol;
13
}
JavaScript
1
8
1
#table {
2
border: 1px solid;
3
}
4
5
th {
6
border: 1px solid;
7
padding: 5px;
8
}
JavaScript
1
9
1
<table id="table">
2
<thead>
3
<th>Number:</th>
4
<th>Word:</th>
5
<thead>
6
<tbody>
7
8
</tbody>
9
</table>
Input:
JavaScript
1
18
18
1
var table = document.getElementById("table");
2
var myBtn = document.getElementById("myBtn");
3
var myInput = document.getElementById("myInput");
4
5
myBtn.addEventListener('click', () => {
6
document.querySelector('tbody').innerHTML = '';
7
var phrase = myInput.value;
8
var words = phrase.split(" ");
9
for (var i = 0; i < words.length; i++) {
10
var tableCol =
11
`<tr>
12
<td>${i+1}:</td>
13
<td>${words[i].replace(/[.,!?]/g," ")}<td>
14
</tr>`;
15
16
document.querySelector('tbody').innerHTML += tableCol;
17
}
18
});
JavaScript
1
14
14
1
input {
2
margin-bottom: 10px;
3
width: 300px;
4
height: 25px;
5
}
6
7
#table {
8
border: 1px solid;
9
}
10
11
th {
12
border: 1px solid;
13
padding: 5px;
14
}
JavaScript
1
12
12
1
<input id="myInput" type="text">
2
<button id="myBtn">Create Table</button>
3
4
<table id="table">
5
<thead>
6
<th>Number:</th>
7
<th>Word:</th>
8
<thead>
9
<tbody>
10
11
</tbody>
12
</table>