ben jay hutton ben jay hutton - 2 months ago 7
HTML Question

JavaScript is appending to a Div tag but with some strange behaviour

I have a script that for every click of the button takes the time, applies @gmail.com to the end and appends it to a defined div tag.

where the problem lies is that every time i hit the button, the first line changes to the current time, an additional line is appended each time with the correct details and they don't update it is just the first line.

can someone suggest a way to stop the first line from updating each time?



function Time() {
var d = new Date();
var dd = d.getDate();
var mm = d.getMonth() + 1; //January is 0!
var yy = d.getFullYear().toString().substr(2, 2);
var j = document.getElementById("demo").innerHTML = dd + "" + mm + "" + yy + "" + d.getHours() + "" + d.getMinutes() + "" + d.getSeconds() + "@gmail.com<br />";

$(document).ready(function() {
$("button").click(function() {
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
$("#demo").append(j);
});
});

return j;

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<h2>Click to generate time</h2>

<button onclick="Time()">Generate</button>

<div id="demo"></div>





What I expect to happen each time i press the button is for it to append the following:

2591695115@gmail.com

2591695116@gmail.com

2591695117@gmail.com

2591695118@gmail.com

...etc

Answer

You are calling Time() onclick in your HTML. You do not need to say $("button").click again in your jquery.

Also, you do not need document.getElementById("demo").innerHTML when assiging the string to var j.

See the following code:

    
    function Time() {
     var d = new Date();
     var dd = d.getDate();
     var mm = d.getMonth() + 1; //January is 0!
     var yy = d.getFullYear().toString().substr(2, 2);
     var j = dd + "" + mm + "" + yy + "" + d.getHours() + "" + d.getMinutes() + "" + d.getSeconds() + "@gmail.com<br />";

        if (dd < 10) {
           dd = '0' + dd
         }
         if (mm < 10) {
           mm = '0' + mm
         }
         $("#demo").append(j);

     return j;

   }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<h2>Click to generate time</h2>
    
    <button onclick="Time()">Generate</button>
    
    <div id="demo"></div>