Ahmed Abbas Ahmed Abbas - 4 months ago 10
Javascript Question

Java Script Get Number of index for array from text box

So here is the problem.I want user to enter number of index in text box for array. After taking index i want user to enter value from a prompt box to store in that array but that prompt box is coming over and over again and i have to click on button every time to take input
Here is the code

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>
<label> Enter Number of Records </label>
<input type="text" id="t1">
<input type="button" value="Enter" onClick="record()">

<h1 id="demo"></h1>

<script src="script.js" type="text/javascript"></script>
</body>
</html>


Java Script:

var data = document.getElementById("t1").value;
function record(){
var crap = new Array(data);
for(var i=0;i<crap.length;i++){
crap[i] = prompt("Add something in my array","");
document.getElementById("demo").innerHTML += crap[i]+"<br>";
}

Answer

Try this,This will solve your issue.

You are just declaring an array named crap, and you are trying to get the crap.length even before the array is filled, so you are getting the issue. Since data has your value try looping with data value.

function record(){
            data = document.getElementById("t1").value;
	    var crap = new Array(data); // you should take data here,  since crap is empty at this point.
            console.log(data)
	    for(var i=0;i<data;i++){
		crap[i] = prompt("Add something in my array","");
	    document.getElementById("demo").innerHTML += crap[i]+"<br>";
	    }
	}
 <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Untitled Document</title>

    </head>

    <body>
    <label> Enter Number of Records </label>
    <input type="text" id="t1">
    <input type="button" value="Enter" onClick="record()">

    <h1 id="demo"></h1>

    <script src="script.js" type="text/javascript"></script>
    </body>
    </html>

Please run the code snippet and check the answer.