Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript Loop based on input

I have a case:
If The user input 3, then the output should be 1 2 start.
If the user input 5, then the output should be 1 2 3 4 start.
If the user input more than 9, then the output should be Error.

I tried the following code, but no idea how can I add the last number into string

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
let text = "";
for (let i = 1; i < 5; i++) {
  if (i == 5) break;
  text += i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>

</body>
</html>

Any idea please?
Really appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you.

>Solution :

Wrap you for loop in a function. Then you can concat the numbers and append the word start on return.

const input = 15;
console.log(countdown(input))

function countdown(input) {
  if (input > 9) {
    return 'Error!';
  }
  c = '';
  for (let i = 1; i < input; i++ ) {
    c += ' ' + i;
  }
  return c + ' start';
}

In your case

    const input = 5;
    
    document.getElementById("demo").innerHTML = countdown(input);
    function countdown(input) {
      if (input > 9) {
        return 'Error!';
      }
      c = '';
      for (let i = 1; i < input; i++ ) {
        c += ' ' + i + '<br/>';
      }
      return c + ' start';
    }
<div id="demo"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading