I'm trying to get a javascript pick a random line from a textarea. Sorry, big noob here.
Currently my code looks like this, and I'm quite sure there are silly mistakes in it. I'm just kinda stuck. First, how do I connect this function to the textarea? Secondly, how do I even output the result? I think I've done too much there with making it two functions. I don't mind making it smaller somehow.
<body>
<div class="container">
<h3>
Enter all of the names on a seperate line. <br />
</h3>
<textarea id="textarea" placeholder="Enter names here..."></textarea>
</div>
<h3>The winner is: <span id = "winner"></span></h3>
<button onclick="randomSelect()">Click me</button>
<script>
function randomSelect() {
const lines = input.split('\n');
const randomLine = lines[Math.floor(Math.random() * lines.length))];
selectOutput();}
}
function selectOutput() {
document.getElementById("winner").innerHTML = ;
}
</script>
</body>
</html>
Your codes should look like below:
<body>
<div class="container">
<h3>
Enter all of the names on a seperate line.
</h3>
<label for="textarea">Enter names: </label><br />
<textarea id="textarea" placeholder="Enter names here..."></textarea>
</div>
<h3>The winner is: <span id = "winner"></span></h3>
<button onclick="randomSelect()">Click me</button>
<script>
function randomSelect() {
const input = document.getElementById('textarea').value;
const lines = input.split('\n');
const randomLine = lines[Math.floor(Math.random() * lines.length)];
//Display your line
document.getElementById('winner').innerHTML = randomLine;
}
</script>
</body>
You just forgot to identify the element from which you are getting the value. But you did well.