简体   繁体   中英

Array sorting: Alphabetical and Numerically

I want a webpage that has a text box. There are two buttons underneath the text box that says "Sort Alphabetically" and "Sort numerically." I want it so that whatever the user types in the box, it sorts. If the user types in numbers and letters, it will cancel the sorting and an alert will pop up saying "Cannot be letters and numbers." When the "Sort Alphabetically" button is clicked, the JavaScript code will activate and sort the words alphabetically. Same goes with the "Sort Numerically" button. I can't seem to get the words/numbers to sort.

HTML:

<html>
<head>
<title>Sorter</title>
<script type="text/javascript" src="sorter.js"></script>
</head>
<body>
<form>
Words/Numbers to Be Sorted:<input type="text" id="textbox" size="35"/>
<br/>
<button type="button" onclick="sortAbc()">Sort Alphabetically</button>
<button type="button" onclick="sortNumber()">Sort Numerically</button>
<br/>
<h1>Each number/word shall be separated by a space.</h1>
</form>
</body>
</html>

JavaScript:

function sortAbc() {
var captureText = document.getElementById('textbox');
captureText.sort();
//Help! How to make alert pop up when numbers and letters are typed?
}

function sortNumber() {
var captureNumb = document.getElementByid('textbox');
captureNumb.sort(function(a, b){return a-b});
//Same problem here! How to make alert pop up when numbers and letters are typed?
}

Here a complet live sample.

  • check for number or words using regular expression ( .match )
  • use the array function sort

 function sortAbc() { var captureText = document.getElementById('textbox'); if (captureText.value.match(/(?:^| )[\\d]+(?: |$)/)) { alert("no digits"); return; } var words = captureText.value.split(" "); captureText.value = words.sort().join(" "); } function sortNumber() { var captureNumb = document.getElementById('textbox'); if (captureNumb.value.match(/[^\\s\\d]/)) { alert("no letters"); return; } var numbers = captureNumb.value.split(" "); captureNumb.value = numbers.sort(function (a, b) { return a - b }).join(" "); } 
 <html> <head> <title>Sorter</title> <script type="text/javascript" src="sorter.js"></script> </head> <body> <form> Words/Numbers to Be Sorted:<input type="text" id="textbox" size="35"/> <br/> <button type="button" onclick="sortAbc()">Sort Alphabetically</button> <button type="button" onclick="sortNumber()">Sort Numerically</button> <br/> <h1>Each number/word shall be separated by a space.</h1> </form> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM