anon anon - 26 days ago 7
Javascript Question

errors with sorting an array

I'm trying to sort the contents of id="demo" with a button , but everytime I click my button I get nothing.

Once the button is clicked I would like select() to be able to read the contents of id="demo" (once the random numbers are outputted) and sort/dump them into id="demo2".

What I think is happening is select() is reading var arr as a blank array, rather than an array with a random assortment of numbers ( as it is at the end of first() )

<input id="input1" type="number" min="10" max="100" onchange="first(); sortButton();">

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

<!-- button appears here, once a value is entered into the input field -->
<p id="buttons1" onclick="select();"></p>


<p id="demo2"></p>

<script>


// once input1 value changes this outputs a random value less than N (value of input1) N times, then dumps out the random numbers in id="demo"

function first() {
var N = document.getElementById("input1").value;
var arr = [];
while(arr.length < N)

{var randomnumber = Math.ceil(Math.random()*N);
arr[arr.length] = randomnumber;}
document.getElementById("demo").innerHTML = arr;}


// Once input1 value changes, this buttons appears in id="buttons"
function sortButton() {document.getElementById("buttons1").innerHTML =
'<button type="button" onclick="select();">Select Sort</button>';}



// meant to sort the random numbers in id="demo" once the button is clicked
function select() {
document.getElementById("demo2").innerHTML = arr.sort(function(a,b){return a - b});}




</script>

Answer

You have to declare var arr = [] outside of your function. Here's a working program. Hope it helps :)

// once input1 value changes this outputs a random value less than N (value of input1) N times, then dumps out the random numbers in id="demo"
var arr = [];

function first() {
var N = document.getElementById("input1").value; 
while(arr.length < N){

  var randomnumber = Math.ceil(Math.random()*N);
  arr[arr.length] = randomnumber;
}
document.getElementById("demo").innerHTML = arr;
}


// Once input1 value changes, this buttons appears in id="buttons"
function sortButton() {
  document.getElementById("buttons1").innerHTML =
'<button type="button" onclick="select();">Select Sort</button>';
}



// meant to sort the random numbers in id="demo" once the button is clicked
function select() { 
document.getElementById("demo2").innerHTML = arr.sort(function(a,b){return a - b});
}
<input id="input1" type="number" min="10" max="100" onchange="first(); sortButton();">

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

<!-- button appears here, once a value is entered into the input field -->
<p id="buttons1" onclick="select();"></p>


<p id="demo2"></p>