Luis Luis - 4 months ago 24
Javascript Question

Rows of 7 with values from Array

I want to create a code that get's the values from array

["1", "2", "3"]
and then it creates a new row with 7 of this. The array will have near 90 values, so from 1-7 is in the first row, 8-14 in another and so. I created this code but it just freezes the website and crashes the browser, so I would like you to tell me where's the mistake.

var newVals = new Array("1", "2", "3"..."81");
var target = ".content table";
var activeTar = target + " .active";
for(var i = 0; i < newVals.length; i++){
for (var y = 0; y < 7; y++){
if(y == 0){
jQuery(target).append('<tr class="active"></tr>');
var valId = newVals[i];
var valImg = "" + valId + "/picture";
var valCode = '<td class="cell"><a class="toggleAdd" tabindex="0" data-icon="'+valId+'"><img src="'+valImg+'"></a></td>';
if(y == 6){
y = -1;
jQuery(".toggleAdd").live("click", function(){
jQuery("input", jQuery(this).closest('form')).val(jQuery("input", jQuery(this).closest('form')).val() + jQuery(this).attr("data-icon"));


Seems like you have the "active" class just for doing DOM selecto to insert into the proper row.

No need. Just save the row in a variable, append to it, and make and save a new row every seven items.

var newVals = new Array("1", "2", "3", /*...,*/ "81"),
    target = jQuery(".content table"),

$.each(newVals, function(i, valId) {
    if(i % 7 === 0)
        activeRow = jQuery('<tr></tr>').appendTo(target);

    activeRow.append('<td class="cell"><a class="toggleAdd" tabindex="0" data-icon="'+valId+'"><img src="' + valId + '/picture"></a></td>');

This uses the modulus operator to determine if it is time to make a new row.

with respect to the handler, you can clean it up a bit if you use variables. Also, if you're using jQuery 1.7 or later, you should use on instead of live.

jQuery(document).on("click", ".toggleAdd", function(){
    var input = jQuery(this).closest('form').find("input"),
        v = input.val() + jQuery(this).attr("data-icon");


You should replace document with a selector that represents the deepest container that holds all the .toggleAdd elements.