Reputation: 161
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?
Upvotes: 1
Views: 192
Reputation: 1228
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.
Upvotes: 2
Reputation: 21
This is not the best way to go about the problem, but.
if('div'.Count >= MaxNumber){
Do Not Add Child.
}else{
Add Child.
}
Upvotes: 1
Reputation: 30993
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/
Upvotes: 1
Reputation: 2930
var maxNumber = this.value;
for (var i=0; i<maxNumber;i++)
just check the value BEFORE the for and not at every step
Upvotes: 1