<!DOCTYPE html>
<html>
<head>
<title>Name List Reversal</title>
<link rel="stylesheet" href="script01.css">
<script src="script03.js"></script>
</head>
<body>
<h2 class="centered">
Reverse a list of names
</h2>
<form action="#">
Enter a list of names with first name first,
one per line:<br>
<textarea id="nameField" class="nameList"
rows="10" cols="50">
</textarea>
<p>
<input type="submit" value="Submit">
<input type="reset">
</p>
</form>
</body>
</html>
body {
color: #000;
background-color: #FFF;
}
input.invalid {
background-color: #FF9;
border: 2px red inset;
}
label.invalid {
color: #F00;
font-weight: bold;
}
.centered {
text-align: center;
}
window.onload = function() {
document.forms[0].onsubmit = validForm;
}
function validForm() {
// Make an array of all tag names in the first form
var allTags = document.forms[0].getElementsByTagName("*");
// Run all tags in the array through validTag function
for (var i=0; i<allTags.length; i++) {
validTag(allTags[i]);
}
return false;
function validTag(thisTag) {
// Split Class of tags with 2 class names on space
var allClasses = thisTag.className.split(" ");
// Hunt for the tag with class name = namelist
for (var j=0; j<allClasses.length; j++) {
if (allClasses[j] == "nameList") {
// only run setNameList on this class
thisTag.value = setNameList(thisTag.value);
}
}
function setNameList(inNameList) {
var newNames = new Array;
var newNameField = "";
var re = /\s*\n\s*/;
// Split the contents based on the Regular Expression
var nameList = inNameList.split(re);
re = /(\S+)\s(\S+)/;
for (var k=0; k<nameList.length; k++) {
// Swap the position of the 2 substrings
newNames[k] = nameList[k].replace(re, "$2, $1");
}
for (k=0; k<newNames.length; k++) {
newNameField += newNames[k] + "\n";
}
return newNameField;
}
}
}
Name Reversal App