user5061223 user5061223 - 2 months ago 14
Javascript Question

Ascending numbers in Javascript

I'm trying to make an html page with javascript and it has to sort the numbers taken from the user from the smallest to the biggest number. I can make a pre defined array one but I can't figure out how to do it with user input. Can anyone give me a hint? Thanks! And I forgot to add that the numbers have to be separated with commas on the input

<html>
<body>


<input type="text" id="userInput" />

<button onclick="myFunction()">Sort</button>



<script>


function myFunction() {
var input = document.getElementById("userInput").value;
var points = [input]
points.sort(function(a, b){return a-b});
document.write(points);


}
</script>

</body>
</html>

Answer Source

You need to split by , or any space characters(tabs, multiple spaces)

function myFunction() {
    var input = document.getElementById("userInput").value;

    if (input) {
        var points = input.split(/\s+|,/); // Split by space characteres or ,

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

    }
}