Prompt user to input information, then sort the data

For a class project, I need to create a program in Javascript that asks a user to input 3 names, then sorts the names alphabetically and prints them on the screen.

I have figured out how to create a prompt box for the user to input the data, and I can get the program to then print the string that the user inputs onto the screen. However, I cannot figure out how to get Javascript to sort the string. I know that I need to use an array, but I'm not sure where to put the array, or how to get it to know user-inputted variables.

This is the code I have so far:

<html>
<script> 

function disp_prompt() 
      {
      var names=prompt("Please enter three names","Names")
      document.getElementById("msg").innerHTML= names
      }

</script> 


<center><input type="button" onclick="disp_prompt()" value="Click Here"></center>
<br>

<h2><center><div id="msg"></div></center></h2>
</html>

Answers:

Answer

The whole thing could look like

var namesToPrompt = 3,
    names         = [ ];

// as long as namesToPrompt is truthy, prompt for inputs
while( namesToPrompt-- ) {
    names.push( prompt('Please enter a name') );
}

// sort our array
names.sort( byName );

// and print it
document.getElementById( 'msg' ).textContent = names.join(',');

function byName( a, b ) {
    return a.localeCompare( b );
}

If you want to let the user enter all names at once, you could go like

var inputNames = prompt( 'Please enter three names','Names' );

document.getElementById( 'msg' ).textContent = inputNames
                                                 .split( /,\s+/ )   // split by any amount of white-space characters in a row
                                                 .sort( byName )
                                                 .join( ',' );

function byName( a, b ) {
    return a.localeCompare( b );
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.