Question

I'm writing a simple little JavaScript and that basically appends an element every time a button is clicked. I also want to limit the number of times the element can be appended via a counter and a conditional statement.

The Fiddle

The Code:

HTML

<p id="moreUpload">click me</p>
<div id="file-uploads"></div>

JavaScript

var div = "<div class='fileupload fileupload-new' data-provides='fileupload'><span class='btn btn-file'><span class='fileupload-new'>Select file</span><span class='fileupload-exists'>Change</span><input type='file' name='file[]' /></span><span class='fileupload-preview'></span><a href='#' class='close fileupload-exists' data-dismiss='fileupload' style='float: none;'>x</a></div>";
var count = 1;

if (count < 6) {
    $("#moreUpload").click(function () {
        $(div).hide().appendTo("#file-uploads").fadeIn(500);
        alert(count);
        count++;
    });
}

Basically as written the JavaScript will allow infinite appends, I assumed incrementation was not working. However the alert calls out the number I expect to see. What am I doing wrong?

Was it helpful?

Solution

try moving your condition inside of click function,because outside of click function it is doing nothing when you click button it only run inside of click events code:

$("#moreUpload").click(function () {
    if (count < 6) {
        $(div).hide().appendTo("#file-uploads").fadeIn(500);
        alert(count);
        count++;

    }
});

Here is demo

OTHER TIPS

$("#moreUpload").click(function () {
    if (count < 6) {
        console.log(count);
        $(div).hide().appendTo("#file-uploads").fadeIn(500);
        alert(count);
        count++;
    }
});

DEMO

Everytime you are change the count variable.But it's on global scoop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top