0

i have to write a program which asks the user in advance how many numbers will be input. Receive that many numbers and output the highest using JavaScript functions. Having a set amount of numbers for the user to enter numbers is no good for this exercise. It needs to be the user who enters the amount of numbers to be entered.

I have made a start, but its not working. Any help would be great!

<P>Numbers Exercise</P>
<p id="numbers"></p>
<input type="button" value="Start" onClick = "numbers();">
<script>
function numbers(){

var numbers = 0;

var outMessage = "";

var numbersArray = new Array(numbers);

do{
numbers = prompt('How many numbers?', 0);
}while(isNaN(numbers));


var arr = []; 
for (var i = 0; i < 20; i++) {
  arr[i] = parseInt(prompt('Enter a number'), 0);
}

var maxNum = Math.max.apply(null, arr);
document.getElementById('result').textContent = maxNum;
}

</script>

</body>
</html>
prince
  • 1
  • 6

1 Answers1

1

Just change the hardcoded 20 to numbers; I ran it and it worked for me... after adding a text field for result

var arr = []; 
for (var i = 0; i < numbers; i++) {
    arr[i] = parseInt(prompt('Enter a number'), 0);
}

then i added a label

<label id='result' />

then fixed your assignment to :

document.getElementById('result').innerHTML = maxNum;

FULL DOCUMENT:

<!DOCTYPE html>
<html>
<head> <meta charset="utf-8" />
<title></title>

<script style="text/javascript">
    function numbers(){
    var numbers = 0;
    var outMessage = "";
    var numbersArray = new Array(numbers);

    do{
        numbers = prompt('How many numbers?', 0);
    }while(isNaN(numbers));


    var arr = []; 
    for (var i = 0; i < numbers; i++) {
      arr[i] = parseInt(prompt('Enter a number'), 10);
    }

    var maxNum = Math.max.apply(null, arr);
    alert(maxNum);
    document.getElementById('result').innerHTML = maxNum;
    // or you can use numbers instead of result.. because of your p tag with 
    // the id of numbers
    }
</script>
<body>
<p>Numbers Exercise</p>
<p id="numbers"></p>
<input type="button" value="Start" onClick = "numbers();">
<!-- here -->
<label id='result' />
</body>
</html>
DWolf
  • 703
  • 1
  • 7
  • 20
  • 1
    That radix should be 10 not 0. – Andy Apr 01 '16 at 15:01
  • Just copied what the OP had, my correction is the for loop conditional.. but it still worked with the parse int radix – DWolf Apr 01 '16 at 15:03
  • i put document.getElementById("numbers").innerHTML = outMessage; but it isnt working – prince Apr 01 '16 at 15:03
  • i added an edit that shows how to get the value to display.. if you want to follow your values throughout the JS code, make sure you add alerts too.. like alert(maxNum); or alert(numbers); where ever you need it – DWolf Apr 01 '16 at 15:05
  • where does go because when i put it in the program did not run at all – prince Apr 01 '16 at 15:07