Sorting a list of items using javascript
I am working on a class assignment in which i need to accomplish the following:
1 User types a list of items into a text box (form field) 2 When the user presses the sort button, the list in the text box is sorted 3 It takes the text from the text box and puts the sorted text back in the text box
Please help!
edit: this is what I have thus far, it isnt working though. thanks guys.
<script type="text/javascript">
function addName()
{
var name2add = document.nameForm.newN开发者_运维百科ame.value;
// is the name 1-15 characters in length?
if (name2add.length > 15 || name2add.length == 0)
{
// no, warn the user
alert("Name must be between 1 and 15 characters long.");
// put the focus and selection back in the name text box
document.nameForm.newName.focus();
document.nameForm.newName.select();
} else {
theSelect = document.nameForm.nameList;
newVal = theSelect.options.length;
//alert(name2add + " will be #" + newVal);
// crate the new Option object to insert into the list
var newOption = new Option(name2add,newVal);
// insert the new option into the list
theSelect.options[newVal] = newOption;
// clear out the name text field and return the focus there
document.nameForm.newName.value = "";
document.nameForm.newName.focus();
}
return;
}
function deleteName()
{
var theSelect = document.nameForm.nameList;
theSelect.options[theSelect.selectedIndex] = null;
return;
}
</script>
</head>
<body>
<form id="form4" name="nameForm" method="post" action="">
<p>
<label>
<input type="text" name="newName" id="newName" />
</label>
</p>
<p>
<input type="button" value="Add Name To List" name="addButton" id="addButton" onclick="addName()" />
</p>
<p>
<label>
<select name="list" size="3" id="nameList" >
</select>
</label>
</p>
<p>
<INPUT TYPE="BUTTON" NAME="sort" VALUE=" Sort "
OnClick="sortOptions(document.nameForm.list)">
</p>
<p>
<input type="button" value="Remove Name From List" name="deleteButton" id="deleteButton" onclick="deleteName()" />
</p>
</form>
Luckily for you, Javascript provides a native sorting algorithm, so you don't have to write one yourself. It's array.sort().
So, basically, get the text from the text box, put the text into an array. Then, run .sort() on the array; then put it back into the text box.
As for getting the text into an array, you might use string.split("\n"), if it's separated by lines, or string.split(","), if it's separated by commas.
var itemsToSort = document.getElementById("text_box")
var arrayToSort = itemsToSort.split("\n")
arrayToSort.sort()
document.getElementById("text_box").value = arrayToSort.join("\n")
for your text box with an id of "text_box".
精彩评论