0
<!DOCTYPE html>
<html>
<head>
<title>Ambiente Web</title>

<script type="text/javascript">
function fibo(num) {
   var f = [];
   for (var c = 0; c < num; c++) {
      f.push((c < 2) ? c : f[c-1] + f[c-2]);
   }
   return f;
}

var aux=document.getElementById('Largo').value;
document.getElementById("textarea").innerHTML = fibo(aux);
</script>

</head>
<body>
    <input type="text" value="" id="Largo" name="largo del arreglo"></input>
<input type="button" value="Calcular" onclick="fibo();"></input>
<textarea id="textarea" readonly rows="5" cols="10"></textarea>
 </body>
 </html>

So the thing is that i am calculating the fibonacci sequence, the function by itself works perfect, but i want someone to put the lenght of the fibonacci sequence in the input type="text" and pass it to the fibo parameters and then the result send it to the textarea but it should work and i dont know what happens. Also i dont know how to make the script only run when clicking de "calcular" button with the onlick.

2 Answers2

0

Put your code in a function, and call that from onclick:

<!DOCTYPE html>
<html>
<head>
<title>Ambiente Web</title>

<script type="text/javascript">
function fibo(num){
 var f = [];
 for (var c = 0; c < num; c++) {
  f.push((c < 2) ? c : f[c-1] + f[c-2]);
 }
 return f;
}

function go(){
 var aux=document.getElementById('Largo').value;
 document.getElementById("textarea").innerHTML = fibo(aux);
}
</script>

</head>
<body>

<input type="text" value="" id="Largo" name="largo del arreglo"></input>
<input type="button" value="Calcular" onclick="go();"></input>

<textarea id="textarea" readonly rows="5" cols="10"></textarea>

</body>
</html>

You may also like to take a read of this question: addEventListener vs onclick which shows some other ways that are used more compared to this inline version.

Joe Iddon
  • 18,600
  • 5
  • 29
  • 49
0
Pass the value of the DOM element in fibo function in following way: 

   <!DOCTYPE html>
   <html>
   <head>
   <title>Ambiente Web</title>

   <script type="text/javascript">
   function fibo(num){

   var f = [];
   for (var c = 0; c < num; c++) {
   f.push((c < 2) ? c : f[c-1] + f[c-2]);
 }

 document.getElementById("textarea").innerHTML = f;
}

</script>

</head>
<body>
    <input type="text" value="" id="Largo" name="largo del arreglo"></input>
    <input type="button" value="Calcular" 
    onclick="fibo(document.getElementById('Largo').value);"></input>
    <textarea id="textarea" readonly rows="5" cols="10"></textarea>
</body>
</html>
Riyaz
  • 51
  • 2
  • It works but it does something pretty weird, in Chrome you put the number in the input text and when submitting in "Calcular" the result appears on the textarea and vanishes almost instantly – bojackhorseman99 Mar 27 '18 at 21:41