简体   繁体   中英

Control number of HTML-Elements by value of input field

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. Eg 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?

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.

var maxNumber = this.value;
for (var i=0; i<maxNumber;i++)

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

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

if('div'.Count >= MaxNumber){
    Do Not Add Child.
}else{
    Add Child.    
}

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM