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(" ") // store input as array of words 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"> <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:
- Tutorial introduction
- Sorting an Array of Objects
- Example- Numbers and Words Sorter