Solving the error in code
There were some typos in your code
Onclick
event listener should be in simple letters as onclick
Since the function is name is defined as save
in JavaScript you can use onclick="save()"
in HTML
If you get the value of textarea
outside the function in the beginning of the script, only the initial value of textarea
will be assigned to heiku
variable. To get the value of textarea
once the user clicks on the button you should move
let heiku = document.getElementById("heiku").value;
into the save
function.
Corrected code will look like below...
<div>
<div>
<h2>You are to write your tought here in this test box and click save</h2>
<label for="heiku" class="label">Your Heiku</label>
<br />
<textarea class="textarea" id="heiku" name="heiku" rows="4" cols="50">
Write your Heiku here
</textarea>
<button class="button" id="submit" onclick="save()">Save</button>
<p class="p" id="heiku_input"></p>
</div>
</div>
<script>
function save(){
let heiku = document.getElementById("heiku").value;
let heiku_input = heiku
document.getElementById("heiku_input").innerText = heiku_input;
console.log(heiku_input);
}
</script>
Achieving the desired result
However the above code might not produce the accurate results you were looking for. The initial text inserted into the textarea
tag in HTML is also counted as it's value by default. To display the initial text you have inserted inside the textarea
to work as a placeholder you can include it in placeholder
attribute.
Also I am not sure why you are once assigning the value of textarea
to variable heiku
and then again assigning heiku
to heiku_input
.
If you prefer to perform more actions with the value of textarea
you can simply assign the value of textarea
to heiku
only.
To make your code more into ES6 standards you can use const
to define the save
function and use const
instead of let
to assign the value of textarea
field to heiku_input
. Read more about the usage here.
Here is the preferable snippet to use.
<div>
<div>
<h2>You are to write your tought here in this test box and click save</h2>
<label for="heiku" class="label">Your Heiku</label>
<br />
<textarea class="textarea" id="heiku" name="heiku" rows="4" cols="50" placeholder="Write your Heiku here"></textarea>
<button class="button" id="submit" onclick="save()">Save</button>
<p class="p" id="heiku_input"></p>
</div>
</div>
<script>
const save = () => {
const heiku = document.getElementById("heiku").value;
document.getElementById("heiku_input").innerText = heiku;
console.log(heiku);
}
</script>