Search code examples
javascripthtmlbuttonon-screen-keyboard

Javascript - How do you set the value of a button with an element from an array?


<html>
<body>
<script type="text/javascript">
    var key = [["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"]];
</script>
<table>
    <tr>
       <td><input type = 'button' value = "key[0][1]" /></td>;
    </tr>
</table>
</body>
</html>

This is a small example above, but I'm basically making an onscreen keyboard and I already have the loop which positions the buttons, however in my loop I try to assign the value of each key similarly to the code above, but instead of printing q w e r t y for each key, it prints key[row][col] for each button. How do I get the letters to appear on the button using a similar method to the above?


Solution

  • The below code generates the keyboard kind of layout that you are expecting:

    <html>
    <head>
    <script type="text/javascript">
    var key = [["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"]];
    </script>
    
    <body>
    <script type="text/javascript">
    for(var i = 0; i < key.length; i++)
    {
        document.write("<div>");
        for(var j = 0; j < key[i].length; j++)
        {
           document.write("<input type='button' value='" + key[i][j] + "'/>");
        }
        document.write("</div>");
    }
    </script>
    </body>
    </html>
    

    enter image description here

    The only thing the second and third row should move right a little bit to look like real keyboard. For this we can do padding for the div tags. Hope this helps you.