6-3 In this assignment you need to create an HTML page that meets the following
ID: 3759846 • Letter: 6
Question
6-3
In this assignment you need to create an HTML page that meets the following requirements
Create an HTML form.
Create and Initialize three arrays.
Use for-loops to populate those arrays.
Add an element to the end of one array.
Remove an element from the end of another array.
Add a new element to the beginning of one array.
Add at least one additional array method of your choice.
Convert an array to a string.
Use the converted string, assign to a string variable, and use it to populate a form field.
Create different functions to handle the operations of steps 4, 5, 6, and 7. (You can create additional array methods.)
Create four or more buttons on the form with different event handlers to start the above functions upon clicking them.
Create an additional button with an event handler to complete the operation in step 10.
Explanation / Answer
use new Array()
This is the most verbose approach. It works as follows:
var colors = new Array();
colors[0] = "green";
colors[1] = "red";
use new Array(item0, item1, item2 ...)
This approach also employs the new Array() constructor, but does so using a more concise formulation. Here's what it looks like:
var colors = new Array("green", "red");
As you might have guessed, you count the index position of an item inside an array starting at 0.
But, is this index position important? Well, yes it is, at least if you want to use the items inside the array, which is most likely the case.
Here's what I mean.
To access data inside the Array object:
//"green" is at index position 0, "red" is at index position 1, etc.
var colors = ["green", "red", "yellow", "orange", "blue"];
var red = colors[1];
document.write(red);
Access all items in the array with a loop:
//use the array from the previous example
var colors = ["green", "red", "yellow", "orange", "blue"];
//use a for loop to access each item in colors
//The array object has a length property
//that contains the size of the array: you can use it in the for loop
for (var i=0; i < colors.length; i++)
{
//You use the counter i to access the index position
document.write(colors[i] + "<br />");
}
//use the array from the previous example
var colors = ["green", "red", "yellow", "orange", "blue"];
for (color in colors)
{
//color is the variable that marks the index position
document.write(colors[color] + "<br />");
}
var colors = ["green", "red", "yellow", "orange", "blue"];
colors[2] = "pink";
//Now you've replaced the item at index position 2,
//the third item called "yellow",
//with "pink"
document.write(colors);
//The code should print:
//green,red,pink,orange,blue ("pink" has replaced "yellow")
To sort array items:
//sort the colors array alphabetically and ascending:
var colors = ["green", "red", "yellow", "orange", "blue"];
var ascendingColors = colors.sort();
//display each value
document.write(ascendingColors);
//This should print:
//blue, green, orange, red, yellow
//build a new array containing number values
var myNumbers = [4, 2, 10, 6, 9];
//build your custom function: this is a simple formula
function sortAscending(a, b)
{
//the formula return a - b sorts the numbers
//from the smaller to the bigger,
//the formula return b - a sorts numbers in descending order,
//that is, from the bigger to the smaller number
return a - b;
}
//pass the sortAscending function as argument to sort()
var sortedAscending = myNumbers.sort(sortAscending);
//print result on the page
document.write(sortedAscending);
//This should print:
//2,4,6,9,10 . Now try sorting in descending order on your own.
How to add data to the Array object:
You can add new items inside an array in different ways. Which method you choose depends largely on your program's requirements.
Add items to the end of the array with push():
//use our old colors array
var colors = ["green", "red", "yellow", "orange", "blue"];
//use push() to add the color "pink" at the end
colors.push("pink");
//print the enlarged array
document.write(colors);
//This should print:
//green,red,yellow,orange,blue,pink
Add items to the beginning of an array with unshift():
Use unshift() to add new items to the start index position of an array. This is easily done.
Just replace push() with unshift() in the previous example, save your work and run the page in a browser. The page should display the color name "pink" at the very start, like so:
pink,green,red,yellow,orange,blue.
remove data from the Array object:
If you want to remove the last item in an array you use pop(). If you want to remove the first item in an array you use shift().
var colors = ["green", "red", "yellow", "orange", "blue"];
//remove "blue" from colors
colors.pop();
document.write(colors);
//This prints: green,red,yellow,orange
//remove "green" from colors
colors.shift();
document.write("<br />" + colors);
//This prints: red,yellow,orange
//on a new line break
Username registration
The HTML document
<!DOCTYPE html>
<html>
<head>
<title>Lesson 13: JavaScript Objects - Arrays</title>
<script type="text/javascript" src="lesson13_tryout.js"></script>
</head>
<body>
<h1>Lesson 13: Register with us</h1>
<p>Register a Username: <input type="text" id="txtName" /></p>
<p><input type="button" id="btnSubmit" value="Register" /></p>
<p id="result"></p>
</body>
</html>
Your program contains:
//global array: it's outside any function
var userNames = ["harry potter", "donald duck", "shrek", "supercoder"];
/*******************************/
//init() function
function init()
{
var myButton = document.getElementById("btnSubmit");
myButton.onclick = registerName;
}
//assign init() function to onload event
>
/********************************************/
//registerName() function: it executes when user clicks the button
function registerName()
{
//set up main vars: Username entered by user,
//a message string to communicate with the user,
//a reference to the paragraph used to display the message,
//and a boolean var (true/false) used as flag:
//if the registration is successful, this is set to true,
//if registration fails, this is set to false. It's initialized as false.
//Notice how you chain getElementById(), value, and toLowerCase
//to store the value entered by the user in lowercase
var newName = document.getElementById("txtName").value.toLowerCase();
var message = "";
var result = document.getElementById("result");
var success = false;
//If the user clicks the button but the inputbox is empty
//we alert the user and stop further program execution:
if (newName == "")
{
alert("Please, enter a Username");
return false;
}
//we loop over each Username stored in the array
//to make sure the Username is not already in existence
for (var i = 0; i < userNames.length; i++)
{
//if we find a Username equal to the newly entered name,
//it means the Username already exists and we can't
//proceed with registration
if (userNames[i] == newName)
{
message = "Sorry, the Username " + userNames[i] + " already exists. Try again";
result.innerHTML = message;
//set the success flag to false so the rest of the program knows
//that registration failed
success = false;
//stop further program execution
return false;
}
//else - if the Username entered by the user
//is not already stored in the application, register new user:
else
{
message = "Great, you've successfully registered with us as " + newName;
result.innerHTML = message;
//set the success flag to true, so the program knows
//the new Username can be added
success = true;
}
}
//Now you're out of the loop
//if registration was successful (success flag is true),
//add new Username to the array with push()
if (success)
{
userNames.push(newName);
}
//display Usernames sorted alphabetically on a new line
result.innerHTML += "<br />" + userNames.sort();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.