4 Replies - 7473 Views - Last Post: 28 August 2012 - 04:40 AM

Generating number of rows based on user input

Posted 27 August 2012 - 01:58 PM

Hi, I'm trying to have the user enter a number and then a certain amount of rows will be created based on that number. So if the user enters 4, there should be 4 elements going down. Each element should also have a number inside of it, 1 to 4 respectively. I know how to prompt the user for input but I'm not sure how to take this input and generate rows with numbers in them. Can anyone give me some hints or point me in the right direction?

Replies To: Generating number of rows based on user input

Re: Generating number of rows based on user input

When dealing with tables: instead of manually creating the table elements with document.createElement, you can use the insertRow and insertCell functions. (See the links for examples.)

You'd get the row count from the user, turn it into a number using the parseInt function, make sure it's a valid number using the isNaN function, and then use a for loop to create the correct amount of rows.

Re: Generating number of rows based on user input

Posted 27 August 2012 - 08:49 PM

No, not really. You seem to have just copied the definition and/or the examples from the MDN docs exactly. That won't work. - You need to read and understand what the code you are trying to copy into your page does.

The definition for parseInt(), as written in the MDN docs, is:

var intValue = parseInt(string[, radix]);

What they are trying to show you there is not how parseInt should look in your code, but how it should be used in your code. - This is explaining that the parseInt() function can take two parameters: First a "string" parameter, which is the numeric string to be converted; and and optional (but encouraged) "radix" parameter for the output number. - The [] brackets around the second parameter means that it's optional.

In typical use, you would just pass the string you want to convert as the first parameter, and 10 as the second parameter. (Assuming you want a decimal number.)

As for the insertRow code. Well, you just copied that exactly, even though it doesn't really fit what you are trying to do. That example was not meant to be used to generate the type of output you seem to want. It's meant to show how it can be used, but they expect you to alter it to fit your situation.

Lastly, after the insertRow code you copied, you've got your for loop code. There are three problems there: First, the code is outside <script> tags. All Javascript code must be inside script tags, or it's just read as part of the HTML page. Second, the var for the table variable is missing the "v". And third, the conditions for the for loop are off. You may want to reread that part of the for loop docs.