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>
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>
Share
Improve this question
asked Mar 21, 2013 at 17:50
Annika ZwirnAnnika Zwirn
12 silver badges2 bronze badges
2
- Theres only one prompt how the user enter 3 names? – Rodrigo Siqueira Commented Mar 21, 2013 at 17:52
-
What have you tried? Do you have any idea of what to do with the string? Hints:
split
,sort
, andjoin
functions – Bergi Commented Mar 21, 2013 at 17:53
1 Answer
Reset to default 4The 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 );
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745298242a4621273.html
评论列表(0条)