Home > Back-end >  Get the returned variable out of a function and into a document.write
Get the returned variable out of a function and into a document.write

Time:11-07

Pretty new to this, but trying to get the output of the fibonacci generator into document.write Instead of just an alert. The point of this project is to have a variable submitted by the user, go through the Fibonacci Generator then get printed to the bottom of the web page.

The error i get is cannot read properties of null (reading classname). I tried searching this site and looked at "document.getElementById('result').className;". Maybe I am using it wrong, any help would be appreciated.

    </head>
<body>
<div class="background-color">
<h1>Welcome to the Fibonacci Generator!</h1>

<h2>Please input a number between 1 and 10</h2>

<div class="container">
<form class="pure-form">
    <input class="numberInputBox" autocomplete="off" id="name" 
type="number" placeholder="            Enter # Here!" />
   <button type="submit" class="btn btn-success heighttext">GO!</button>
</form>

<script type="text/javascript">  

var nameInput = document.getElementById('name');

document.querySelector('form.pure-form').addEventListener('submit', 
function (e) {

    e.preventDefault();

      //fibonacciGenerator

      var arrayNumber = [];
      var yourNumber = (nameInput.value);
      function fibonacciGenerator(n) {
      for(var i=0; i<n; i  ) {
       if (arrayNumber.length == 0) {
           arrayNumber.push(0)
       } else if (arrayNumber.length == 1) {
           arrayNumber.push(1)
       } else {
           arrayNumber.push(arrayNumber[(arrayNumber.length - 1)]  
      arrayNumber[(arrayNumber.length - 2)]);
       }
      }
      return arrayNumber;
      }
      var result = fibonacciGenerator(yourNumber);
      var number = alert(result);
      });



  </script>
  </div>
  <div class="display"> 
  <script type="text/javascript">
  </script>

  <h1>

  <script type="text/javascript">
      var number = document.getElementById('number').className;
      document.write(number);
  </script>

  </h1>

    </div>
    </div>
    </div>
    </div>
    </div>
    </body>
    </html>
    <footer>
    <div class="footer">
    </div>
    </footer>

CodePudding user response:

Here's a very simple example of passing the result of a fibonacciGenerator function to document.write.

function fibonacciGenerator(n) {
  var seq = [0, 1];
  for (var i = 2; i < n; i  ) {
    seq.push(seq.at(-1)   seq.at(-2));
  }
  seq.length = n;
  return seq;
}

document.write(fibonacciGenerator(10));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

If you trying to get "result" by using document.getElementById, that doesn't work. getElementById return a tag from the DOM.

You the to attached the var "result" to some tag in you DOM.

  • Related