ariefbruce ariefbruce - 1 month ago 8
jQuery Question

How to add element with jquery append and set text value increase

Here's my code:

$("#btn").click(function() {
var total = 1;
if (total<10) {
total = total + 1;
text = '<p>text '+ total +'</p>';
$("#box").append(text);
}
});


View:

<button id="btn">button</button>

<div id="box"></div>


Result:

<p>text 2</p>
<p>text 2</p>


How to make value increase every click button?


Like this:

<p>text 1</p>
<p>text 2</p>
<p>text 3</p>

Answer

If you define total out the of the click scope (as global) you will be succeed what you've tried.

var total = 1;

$("#btn").click(function() {

     if (total<10) {
        total = total + 1;
        text = '<p>text '+ total +'</p>';

        $("#box").append(text);
     }
});