djmayank
djmayank

Reputation: 392

Javascript arranging in ascending order not working

I was trying sorting numbers in ascending order using javascript and i am stuck. HTML:

<h2>JavaScript Array Sort</h2>

<p>Click the button to sort the array in ascending order.</p>

<button onclick="myFunction()">I will arrange</button>

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

</body>

JS:

var points = [7, 1, 6, 3, 5, 2];
document.getElementById("demo").innerHTML = points;    

function myFunction() {
    points.sort(function(a, b){return a - b});
    document.getElementById("demo").innerHTML = points;
}

js fiddle link: https://jsfiddle.net/djmayank/uef3xexk/
I am not getting my mistake. Any kind of help is appreciated.

Upvotes: 1

Views: 192

Answers (2)

Willie
Willie

Reputation: 106

Are you developing this in jsfiddle? If so, in the javascript settings, change when the code is loaded to "in the body".

Otherwise, you want

document.getElementById("demo").innerHTML = points;

to be run when the document body is rendered because you need #demo to be in the dom to add the list to it.

// example onload on body
<body onload="initalDemoInnerHtml()">

// js code
function initalDemoInnerHtml() {
  document.getElementById("demo").innerHTML = points;
 }

myFunction() should be defined in the same script tag as the code above.

<script type="text/javascript">
  var points = [7, 1, 6, 3, 5, 2];
  function initalDemoInnerHtml() {
   document.getElementById("demo").innerHTML = points;
  }
  function myFunction() { 
   points.sort(function(a, b){return a - b});
   document.getElementById("demo").innerHTML = points; 
  }
</script>

This script should be added to be to the head tag.

Upvotes: 1

Miguel
Miguel

Reputation: 20633

You need to call the function using an event handler unless using No wrap - in <body> option in JSFiddle.

JS

var submit = document.querySelector('#submit')
var output = document.getElementById('demo')

var points = [40, 100, 1, 5, 25, 10];

output.innerHTML = points;

function sortArray() {
  points.sort(function(a, b) {
    return a - b
  });

  output.innerHTML = points;
}

submit.addEventListener('click', function(event) {
  event.preventDefault()

  sortArray()
})

HTML

<h2>JavaScript Array Sort</h2>

<p>Click the button to sort the array in ascending order.</p>

<button id="submit">I will arrange</button>

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

JSFiddle demo: https://jsfiddle.net/uef3xexk/3/

Upvotes: 3

Related Questions