Categories:
Partners
Web Hosting
We've partnered with HostGator for reliable, affordable hosting starting at $3.95/mon. Use coupon code "javascriptkit25" for 25% off any package.

Example: Numbers and Words Sorter

Lets create a script now that accepts any string value and sorts it either alphabetically or numerically:

Enter into the following text box "34 22 23 435 33 2 1 43 54", for example, and press the sort numerically button. Or, try entering "this is a test", and press the sort alpha button.

<script type="text/javascript">

function sortit(a,b){
return(a-b)
}

function sortvalues(param){
var inputvalues=document.sorter.sorter2.value.split(" ")
if (param==0) //if sort alphabetically
inputvalues.sort()
else //else if sort numerically
inputvalues.sort(sortit)
document.sorter.sorter2.value=''
for (i=0;i<inputvalues.length-1;i++)
document.sorter.sorter2.value=document.sorter.sorter2.value+inputvalues[i]+" "
document.sorter.sorter2.value+=inputvalues[inputvalues.length-1]
}
</script>

<form name="sorter">
<p>
<textarea rows="10" name="sorter2" cols="50" wrap="virtual"></textarea><br>
<input type="button" value="Sort alphabetically" onClick="sortvalues(0)">
<input type="button" value="Sort numerically" onClick="sortvalues(1)">
<input type="reset" value="Reset">
</form>

To make sure it works:


Copyright 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.