I’m very new to javascript and I can’t find my mistake. I have an input field and I want to display the value entered in the input field in the section below, once the button is clicked.
I’ve added a click event listener on the button and tried to write a function, which would create a new p element, after the button is clicked, but that doesnt work.
"use strict";
let button = document.getElementById('btn');
button.addEventListener("click", function() {
let answer = document.createElement('p');
let input = document.getElementById('input').value;
answer.innerHTML = "<p>" + input.value;
console.log('log for testing')
})
body {
margin: 0 auto;
background-color: rgb(149, 199, 255);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
header {
background-color: rgb(14, 131, 240);
height: 170px;
width: 100%;
position: fixed;
}
h2 {
display: flex;
justify-content: center;
align-items: center;
color: white;
letter-spacing: 2px;
font-size: 30px;
}
#input {
display: inline;
width: 400px;
border-radius: 8px;
border: none;
height: 40px;
margin-right: 2px;
padding-left: 8px;
margin-left: 10px;
}
#btn {
font-size: 24px;
border: none;
height: 42px;
width: 42px;
border-radius: 8px;
font-weight: 700;
transition: 0.3s;
}
#btn:hover {
cursor: pointer;
}
#btn:active {
background-color: rgb(201, 199, 199);
}
form {
display: inline-flex;
}
section div {
background-color: rgb(157, 157, 240);
height: 100%;
width: 444px;
color: white;
top: 200px;
position: fixed;
margin: 0;
border-radius: 8px;
padding: 8px;
margin-left: 10px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>input to innerHTML</title>
</head>
<body>
<header>
<h2>Enter your text below</h2>
<form id="form">
<input id="input" type="text" placeholder="Write something here...">
<button id="btn" type="button"> + </button>
</form>
</header>
<main>
<section>
<div id="answer-section">
<p></p> <!-- all the answers should go here -->
</div>
</section>
</main>
<script src="script.js"></script>
</body>
</html>
Can anybody see my mistake or point me to the right direction? Any help would be much appreciated, thanks.