shubham
shubham

Reputation: 43

Add new user data to div

I am trying to learn JavaScript. I have a question which might sound silly, but I would really appreciate the help. I have the following code:

JavaScript

<script type="text/javascript">    
function fn(){
    var Name = document.getElementById('name').value;       
    document.getElementById('result').innerHTML = Name;
}    
</script>

HTML:

<body>
<input type="text" id="name" placeholder="enter">
<br>
<button id="btn" onclick="fn()">click</button>
<div>
    <p id="result"></p>
</div>
</body>

I want to save every entry in of my textbox. Right If I am trying enter a new data input box, it replaces the previous data.

Upvotes: 0

Views: 191

Answers (2)

Mechanic
Mechanic

Reputation: 5380

This will solve your problem;

<script type="text/javascript">    
function fn(){
    var Name = document.getElementById('name').value;       
    document.getElementById('result').innerHTML += Name;
}    
</script>

notice the += instead of =; it will get the previous value first, then add the new value to the end of it;

same as:

document.getElementById('result').innerHTML = document.getElementById('result').innerHTML + Name;

Upvotes: 2

elvira.genkel
elvira.genkel

Reputation: 1333

In your JavaScript code only the last attempt is saved. To save all the attempts try the following:

<script type="text/javascript">    
function fn(){
    var Name = document.getElementById('name').value;       
    document.getElementById('result').innerHTML += Name +'<br/>';
}    
</script>

Every time button is clicked it will add new line symbol and new value to your result area, not relace previous try.

Upvotes: 1

Related Questions