Jordan Shoemaker Jordan Shoemaker - 1 month ago 4
Javascript Question

Why can't I use this variable in my for loop?

Long time lurker and first time poster here.

So I am having an issue with running the loop for this function. It does not appear I can use var formappend in the for loop, even though my var formappend returns a number to the console when I input a number into the form.

var formappend = $('input[name=inputform]').val();
for (var i = 0; i < formappend; i++){
$('button').one('click', function(i) {
var newblock = $("<div class='block'></div>").text("");
$('#funbox').append(newblock);
});
}


Thanks

Answer

First of all, you need to run 'for' loop inside the click handler. Currently you bind a click handler inside a 'for' loop, so try this:

$('button').on('click', function(i) {
    $('#funbox').text('');
    var formappend = parseInt($('input[name=inputform]').val());
    if(isNaN(formappend)) return false;

    for (var i = 0; i < formappend; i++){      
        var newblock = $("<div class='block'></div>").text("");
        $('#funbox').append(newblock);
    }
});

Check this out: https://jsfiddle.net/s24edozb/5/

Comments