My goal is for the user to be able to enter a block of text and have it returned in a user-friendly format, like a blog post. They’ll enter in their name and whatever they want to say, then it will be stored locally and displayed. I’ve tried storing the data as local storage, but I keep getting an error with "this file does not exist". The code snippet below is just for a basic displaying once the user clicks a button, but even that doesn’t work.
Please note this all needs to be able to function independently, as I’m teaching myself basic Javascript/HTML for a coding competition where the only software allowed is notepad for coding and Photoshop for image manipulation.
<!DOCTYPE html>
<html>
<script>
function passvalues() {
var firstName = document.getElementById("txt".value);
localStorage.setItem("textvalue",firstName);
}
document.getElementById("result").innerHTML = localStorage.getItem("textvalue");
</script>
<body>
<form>
<input type = "text" id ="txt" placeholder='place text here'/>
<button type="submit" value='click me!' onClick="passvalues();"> Click Me</button>
</form>
</body>
<p id="result"></p>
</html>
Hi everyone, I’m sorry I didn’t get to this sooner! In any case, thank you to all of those who answered, it’s highly appreciated.
4
Answers
You got the right ideas. The biggest problem is in here:
I’ll let you figure out what’s wrong there.
Some other things to fix:
<p>
is inside the<body>
<script>
is inside the<body>
and after the HTML elements it operates on, so basically make it the last thing in the<body>
Another tip is that you may or may not want to add
return false;
at the end of your onClick javascript. This will prevent it from submitting the form and hence refreshing the page. In this particular case with the design you have, you may actually want to leave it as-is and have the refresh happen so your read from local storage will execute. But, it’s good to be aware of what return false does — as there are a lot of situations in which it isn’t desirable for a form to submit after executing some javascript like that.See: https://jsfiddle.net/9ycqjsuo/ for a working example.
Some things I noticed:
type="button"
to prevent a submit.This will work:
You have 3 issues :
1. getElementById(“txt”.value) should be getElementById(“txt”).value
2. take the
<p>
tag within</body>
3. place the whole
<script>...</script>
just before</body>