2

Given that I have an array of alphabetical characters:

var qwerty = [['q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p'], ['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l'], ['z', 'x', 'c', 'v', 'b', 'n', 'm']];

How would I present them in three rows like on a conventional keyboard using JS without resorting to something like this:

<input type='button' value='Q' id='bt1'/>
<input type='button' value='W' id='bt2'/>
<input type='button' value='E' id='bt3'/>
<input type='button' value='R' id='bt4'/>
<input type='button' value='T' id='bt5'/>
<input type='button' value='Y' id='bt5'/>
<input type='button' value='U' id='bt7'/>
<input type='button' value='I' id='bt8'/>
<input type='button' value='O' id='bt9'/>
<input type='button' value='P' id='bt10'/>
<br>
<input type='button' value='A' id='bt11'/>
<input type='button' value='S' id='bt12'/>
<input type='button' value='D' id='bt13'/>
<input type='button' value='F' id='bt14'/>
<input type='button' value='G' id='bt15'/>
<input type='button' value='H' id='bt16'/>
<input type='button' value='J' id='bt17'/>
<input type='button' value='K' id='bt18'/>
<input type='button' value='L' id='bt19'/>
<br />
...

Many thanks in advance!

1
  • You could use almost any element to represent them, from divs to buttons and spans. You should go with whatever has more semantic meaning to your solution. If you're aiming for a keyboard then buttons is the way to go. Commented Dec 1, 2011 at 1:52

1 Answer 1

6

You would use a nested loop:

var counter = 0;
for (var i = 0; i < qwerty.length; i++) {
   for(var j = 0; j < qwerty[i].length; j++) {
      document.write("<input type='button' value='" + qwerty[i][j] + "' id='bt" + counter++ + "'/>");
   }
   document.write("<br>"); 
}

IF you're interested, here's a cleaner jQuery solution for adding the new buttons, so you don't have to use document.write

<div id="qwertDiv" />

var counter = 0, newDiv;
for (var i = 0; i < qwerty.length; i++) {
   newDiv = $("<div />");
   for(var j = 0; j < qwerty[i].length; j++) {
      newDiv.append($("<input type='button' />")
                        .val(qwerty[i][j])
                        .attr("id", "bt" + counter++));
   }
   $("#qwerty").append(newDiv).append("<br>"); 
}
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.