0

I have simple code, in input user inputs number and it must print the numbers until the input is not equal to zero.

And the problem is when i submit value, page stops responding

Here is how my code looks like:

 window.onload = function() {
    
    var btn = document.getElementsByClassName('btn')[0];
    
    function printInput() {
    	var output = document.getElementsByClassName('output')[0];
    	var input = document.getElementsByClassName('input')[0].value;
    
    	 while(input !== 0) {
         var input = document.getElementsByClassName('input')[0].value;
    		output.innerHTML += input+'<br>'; 
    	}
    }
    	btn.addEventListener('click', printInput);
    
    }
       
  
    	<input type="text" class="input" maxlength="1">
    	<button class="btn">Submit</button>
    	<div class="output"></div>

2 Answers 2

2

The value property of input is a string.

You must compare with the correct type:

while (input !== '0')

or

while (input != 0)

----- edit -----

Consider changing the while to an if, otherwise it will print any number different of 0 indefinitely.

 window.onload = function() {
    
    var btn = document.getElementsByClassName('btn')[0];
    
    function printInput() {
    	var output = document.getElementsByClassName('output')[0];
    	var input = document.getElementsByClassName('input')[0].value;
    
    	 if(input !== '0') {
         var input = document.getElementsByClassName('input')[0].value;
    		output.innerHTML += input+'<br>'; 
    	}
    }
    	btn.addEventListener('click', printInput);
    
    }
       
  
    	<input type="text" class="input" maxlength="1">
    	<button class="btn">Submit</button>
    	<div class="output"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks i don't know why i decided to use while loops for this easy thing
0

You need to make two changes

  • Change type attribute from text to number
  • Change from while to if

Demo

window.onload = function() 
{
  var btn = document.getElementsByClassName('btn')[0];
  function printInput() 
  {
    var output = document.getElementsByClassName('output')[0];
    var input = document.getElementsByClassName('input')[0].value;
    if (input !== 0) 
    {
      var input = document.getElementsByClassName('input')[0].value;
      output.innerHTML += input + '<br>';
    }
  }
  btn.addEventListener('click', printInput);
}
<input type="number" class="input" maxlength="1">
<button class="btn">Submit</button>
<div class="output"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.