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?

Était-ce utile?

La 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

Autres conseils

$("#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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top