2

I am looking to create a grid of 3x3 text input boxes, relative to an existing square div, using pure JavaScript. Preferably I would like to construct the grid of a single 1D array that cycles through every third box (if not, then an array of an array of input boxes would do - I hope this makes sense). This is what my code looks like at the moment, but only three of the boxes show when I cycle the array length (if I don't then the array extends linearly across beyond the div confines):

var row0 = new Array(9);

for (var i = 0; i < 9; ++i)
     {
            row0[i] = document.createElement('input');
            row0[i].style.position = "absolute";
            row0[i].type = "text";  
            row0[i].style.marginLeft = 35px *i % 105  + "px";
            row0[i].style.width = "35px";
            row0[i].style.height = "35px";
            document.getElementById('block1').appendChild(row0[i]);      
     }

How can I get the grid to display correctly?

4
  • You may want to use classes here Commented Apr 11, 2014 at 21:55
  • why don't you just create a <table> of textboxes ? Commented Apr 11, 2014 at 22:00
  • All of your 9 elements are being generated, but they're being stacked on top of each other. You need to apply the margin-left type logic to position the blocks vertically. Something like a margin-top of 0, 35, and 70 depending on the value of i. Commented Apr 11, 2014 at 22:09
  • I did try to use marginTop with 'i' but it creates a diagonal distribution as i changes with each iteration. Commented Apr 12, 2014 at 21:06

1 Answer 1

1

I would use a combination of javascript and CSS

DEMO http://jsfiddle.net/x8dSP/3010/

JS

window.onload = function () {
    var parent_div = document.createElement("div")
    parent_div.id = "parent"
    document.body.appendChild(parent_div);

    var x = 0;
    while (x < 9) {
        var child_input = document.createElement("input")
        child_input.className = "child"
        document.getElementById(parent_div.id).appendChild(child_input);
        x++;
    }
}

CSS

div {
    width: 150px;
}
input {
    display: inline-block;
    width: 30px;
    height: 30px;
    margin: 5px;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.