0

I have this problem I have been working on for a few days. I need to make a page that requests the user for 12 letters, and click the submit button. I cannot make what I have come up with work. Suggestions are welcomed! The Javascript that is run should do the following: Generate a random number 1-3, for the number of rows, and put the 12 characters into a formatted table. For example, a random generated table might produce the following:

Text entered: abcdefghijkl

 a b c
 d e f
 g h i 
 j k l

Or:

 a b c d
 e f g h
 i j k l

etc.

My HTML:

<form name="table">
<p>Enter 12 letters</p>
<input type="text" id= "userVal" size="12">
<input type="button" value="submit"  onclick="createTable()">

Javascript:

var numrows= randomnumber=Math.floor(Math.random()*4)
var numcols=4
document.write ("<table border='1'>")

for (var i=1; i<=numrows; i++)
{
    document.write ("<tr>");
    for (var j=1; j<=numcols; j++)
    {
            document.write ("<td>" + i*j + "</td>");
    }

    document.write ("</tr>");
}


document.write ("</table>");

function createTable(){
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
swam
  • 293
  • 6
  • 19
  • You can't use `document.write` once the page has been loaded -- well, not without destroying the current page. See this page for working with tables: http://stackoverflow.com/questions/171027/add-table-row-in-jquery/171049#171049 – Jeremy J Starcher Mar 14 '14 at 01:38

1 Answers1

0

See if this is the behavior you are looking for:

http://jsfiddle.net/sDbkw/

I modified the loops to be zero based and referenced the textbox:

var createTable = function () {
   var numrows = Math.floor(Math.random()*3) + 1; // x3 gets 0, 1, or 2 so increment 1
   var numcols = 12 / numrows; // if always printing 12 chars
   var userText = $('#userVal').val();
   var output = "<table border='1'>";

   for (var i=0; i < numrows; i++)
   {
       output += "<tr>";
       for (var j=0; j<numcols; j++)
       {
           output += '<td>' + userText[i*numcols + j] + '</td>';
       }

       output += "</tr>";
   }

   output += "</table>";
   $('#output').html(output);
};
Paul Way
  • 1,966
  • 1
  • 13
  • 10
  • This is more towards the behavior I need. Numrows however and producing more than 3 rows for some reason. Also, I am really novice when it comes to javascript, some of the syntax I am unfamiliar with such as the "$" symbol and the use of "#". – swam Mar 14 '14 at 02:16
  • I haven't got into jquery yet, and was trying to use just javascript – swam Mar 14 '14 at 02:22
  • Ahh, this is more familiar. How can I set this up to allow the user to enter what they want and the characters they enter are put into the table. Also, in this code, how is the function called without the "onclick"? – swam Mar 14 '14 at 02:47
  • JSFiddle needs the onclick like I set at the last line of the code. I would just add it to the like you had it already eg. ```` – Paul Way Mar 14 '14 at 02:53