I would like to read all values from a text field/text box individually and then write them to a table:
Example:
This is an example of a text I want to read out.
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:
var table = document.getElementById("table"); var phrase = "This is an example of a text I want to read out"; var words = phrase.split(" "); for (var i = 0; i < words.length; i++) { var tableCol = `<tr> <td>${i+1}:</td> <td>${words[i].replace(/[.,!?]/g," ")}<td> </tr>`; document.querySelector('table tbody').innerHTML += tableCol; }
#table { border: 1px solid; } th { border: 1px solid; padding: 5px; }
<table id="table"> <thead> <th>Number:</th> <th>Word:</th> <thead> <tbody> </tbody> </table>
Input:
var table = document.getElementById("table"); var myBtn = document.getElementById("myBtn"); var myInput = document.getElementById("myInput"); myBtn.addEventListener('click', () => { document.querySelector('tbody').innerHTML = ''; var phrase = myInput.value; var words = phrase.split(" "); for (var i = 0; i < words.length; i++) { var tableCol = `<tr> <td>${i+1}:</td> <td>${words[i].replace(/[.,!?]/g," ")}<td> </tr>`; document.querySelector('tbody').innerHTML += tableCol; } });
input { margin-bottom: 10px; width: 300px; height: 25px; } #table { border: 1px solid; } th { border: 1px solid; padding: 5px; }
<input id="myInput" type="text"> <button id="myBtn">Create Table</button> <table id="table"> <thead> <th>Number:</th> <th>Word:</th> <thead> <tbody> </tbody> </table>