Write a script that inputs a telephone number as a string in the form (555) 555-
ID: 3546097 • Letter: W
Question
Write a script that inputs a telephone number as a string in the form (555) 555-5555. The script should use String method split to extract the area code as a token, the first three digits of the phone number as a token and the last four digits of the phone number as a token. Display the area code in one text field and the seven-digit phone number in another text field.
i have the following code but it doesnt seem to work.
<html>
<head><title> Splitting number</title>
<script type = "text/javascript">
function parseNumber() {
var myForm = document.getElementById( "myForm" );
// clear output fields
myForm.areaCode.value = "";
myForm.number.value = "";
var completeNumber = myForm.input.value;
// split area code and local number
var tokens = completeNumber.split( " " );
var areaCode = tokens[ 0 ];
// split the remaining numbers into two tokens
var tokens2 = tokens[ 1 ].split( "-" );
var exchange = tokens2[ 0 ];
var number = tokens2[ 1 ];
// strip parentheses from area code
areaCode = areaCode.substr( 1, 3 );
// output area code
myForm.areaCode.value = areaCode;
// output combination of exchange and number
myForm.number.value = exchange + "-" + number;
}
// end function parseNumber
// -->
</script>
</head>
<body>
<form id = "myForm" action = "">
<table border = "1">
<tr>
<td>Enter a phone number <br /> [in the form (555) 555-5555]
</td>
<td>
<input name = "input" type = "text" size = "40" />
</td>
</tr>
<tr>
<td>
<input type = "button" value = "Split"
onclick = "parseNumber()" /> </td>
</tr> <tr>
<td>Area code:</td> <td>
<input name = "areaCode" type = "text" size= "5" />
</td>
</tr> <tr>
<td>Number:</td> <td>
<input name = "number" type = "text" size = "8" />
</td>
</tr>
</table>
</form>
</body>
</html>
Explanation / Answer
<html>
<head><title> Splitting number</title>
<script type = "text/javascript">
function parseNumber() {
var myForm = document.getElementById( "myForm" );
myForm.areaCode.value = "";
myForm.number.value = "";
var completeNumber = myForm.input.value.replace(/s/g, '');
var areaCode = completeNumber.substr(1,3);
var tokens2 = completeNumber.substr(5).split( "-" );
myForm.areaCode.value = areaCode;
myForm.number.value = tokens2[0] + "-" + tokens2[1];
}
</script>
</head>
<body>
<form id = "myForm" action = "">
<table border = "1">
<tr>
<td>Enter a phone number <br /> [in the form (555) 555-5555]
</td>
<td>
<input name = "input" type = "text" size = "40" />
</td>
</tr>
<tr>
<td>
<input type = "button" value = "Split"
onclick = "parseNumber()" /> </td>
</tr> <tr>
<td>Area code:</td> <td>
<input name = "areaCode" type = "text" size= "5" />
</td>
</tr> <tr>
<td>Number:</td> <td>
<input name = "number" type = "text" size = "8" />
</td>
</tr>
</table>
</form>
</body>
</html>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.