I have created an index file so that the information entered here is added to the created element
this is for a review section
the index.html
file is here, and includes the CSS and js
let name = document.querySelector('.name').value;
let message = document.querySelector('.message').value;
let btn = document.getElementById('button');
let div = document.querySelector('.items')
btn.addEventListener('click', ()=>{
let item = document.createElement('div')
let inner = `
<h3>${name}</h3>
<p>${message}</p>
`
item.className = "message-item"
item.innerHTML = inner
div.append(item)
});
html, body{
padding: 0;
margin: 0;
}
.msg{
padding: 2em;
margin: 2em;
border-radius: 2vh;
height: 70vh;
display: flex;
align-items: center;
justify-content: left;
flex-direction: column;
background-color: #1e90ff;
}
.items{
height: 65vh;
overflow: scroll;
color: white;
width: 100%;
overflow-x: hidden;
margin: 10px;
}
input{
padding: 10px;
border: none;
border-radius: 8px;
outline: none;
font-size: 1em;
}
#button{
padding: 10px 20px;
border-radius: 8px;
border: none;
font-size: 1em;
}
.button{
padding: 10px 20px;
border-radius: 8px;
border: none;
font-size: 1em;
}
.message-item{
background-color: black;
padding: 1em;
border-radius: 8px;
margin: 3px;
}
<!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">
<title></title>
</head>
<body>
<div class="msg">
<div class="items"></div>
<div class="input">
<input type="text" class="name" placeholder="Name">
<input type="text" class="message" placeholder="Message">
<button id="button">Submit</button>
<button type="reset">Reset</button>
</div>
</div>
</body>
</html>
So I am expecting it to append the elements which have different values
example once i enter the **name **"harry" and **message **as "this is the message"
and then i reset and enter another **name **and **message **then the newly created element should display the newly entered **name **and message
3
Answers
You get the values from your inputs before they are filled. They are just string values and do not update dynamically when the input changes.
I moved these lines to inside your function so that you get the most recent data every time you click the button.
Your
name
variable should be a pointer to the element, not the value.Also, you should clear the input after adding.
A better approach
A better example would be to use a form. This way you can take advantage of built-in form validation, submission, and resetting.
For example, you can call elements by their name and you have the added bonus of Enter key support.
You need to get the values of your input on every button submit button press, not just once on page load, and also you need to clear your inputs when you press the reset button