1

I'm trying to build a JavaScript-based Layout grid generator where I want to control the number of grid rows by the value of an input field. E.g. if I type in 12, my container-div should have 12 divs within. I already made a function that can handle this...

document.getElementById('numofrows').onkeyup=function(){
    var foo = [];
    for (var i=0; i<this.value ;i++) {
        foo[i] = document.createElement('div');
        container.appendChild(foo[i]);

    }
}

...But its drawback is, that every further input I make will add a number of divs again. How can I restrict the total number of child divs to what is just the actual value of the input field?

4 Answers4

2

If you want to make it dynamic, every time the function executes, just clear the container div and add the number of divs corresponding to the input value. Like this:

document.getElementById('numofrows').onkeyup=function(){
    document.getElementById('container').innerHTML='';
    var foo = [];
    for (var i=0; i<this.value ;i++) {
        foo[i] = document.createElement('div');
        container.appendChild(foo[i]);

    }
}

Else a simple if else block should be fine for you.

Ritikesh
  • 1,228
  • 1
  • 9
  • 19
1
var maxNumber = this.value;
for (var i=0; i<maxNumber;i++)

just check the value BEFORE the for and not at every step

MrPk
  • 2,862
  • 2
  • 20
  • 26
1

This is not the best way to go about the problem, but.

if('div'.Count >= MaxNumber){
    Do Not Add Child.
}else{
    Add Child.    
}
Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111
StarScript
  • 21
  • 1
1

You can clear your children divs first, and then add the new list; like:

document.getElementById('numofrows').onkeyup = function () {
    var foo = [];

    // remove all the children of the parent element container
    while (container.firstChild) container.removeChild(container.firstChild);

    for (var i = 0; i < this.value; i++) {
        foo[i] = document.createElement('div');
        container.appendChild(foo[i]);

    }
}

Demo: http://jsfiddle.net/IrvinDominin/56VeH/

Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111