Question

In: Computer Science

n this assignment, you will need to code a Web page that will allow a user...

n this assignment, you will need to code a Web page that will allow a user
to enter their first and last names and indicate how many pets they have, if any.

If they have pets, the user will be able to list up to three of their names.

You will code validations on some of the fields and display error
messages on the page when a field does not pass the validation test.

If all the data entered is valid, you will display a specially formatted
message as the last item on the page.
1.  The First Name, Last Name, and "How Many Pets" fields must
not be empty.

2.  The "How Many Pets" field must be a valid number and must be
between 0-3.


Success

If all the data are entered correctly, which means no errors were found, your program
must do the following...

1.  Get today's date into a format like so:   10-22-2013

2.  Put the first and last names in the following format:  "Last, First"
     (for example my name would display as "Perry, Steve"

3.  Use a for-loop to retrieve the value for each Pet name entered
up to the value that the user entered in the "How Many Pets" field.

As the loop is processing, you will need to append each pet's name to a string variable to
store all of the pet names.  This string variable will be used later for display in the message
at the end of the page.

I have given the pet fields "id" values like so...

                <input type="text" id="pet1">
                <input type="text" id="pet2">
                <input type="text" id="pet3">

... your for-loop must use the counter variable to build the
name of the id for the pet field  being processed in that
iteration of the loop.

Something like...

                  for(counter=1; counter<=NumOfPetsEntered; counter++)
                  {
                        myPetId = 'pet' + counter;
                        myPetName = document.getElementById(myPetId).value;

                        // Code to append test into a message variable
                  }
Show an error message for ALL fields that are in error!
Do not just show one error at a time.


One approach you can take is to set a "flag" variable to indicate
that an error has been found, as you find each error. Then, after
all the validations are completed, check the flag to see if any
errors were found.

Conceptually the logic is ...


        var errorFoundFlag = 'N';  //Initialize variable to 'N'

        if (something is found to have an error)
        {
                msg += "error found with something";
                errorFoundFlag = 'Y';
        }

        if (somethingElse is found to have an error)
        {
                msg += "error found with somethingElse ";
                errorFoundFlag = 'Y';
        }

        if (errorFoundFlag == 'N')
        {
           Do the processing called for in the "Success" section above
        }


Use Functions in your JavaScript code


1.  Use the $ shortcut function for document.getElementById

                var $ = function (id) {
                        return document.getElementById(id);
                }
                
                
2.      Put the main JavaScript code that processes the program inside a function 
        that is called when     the button is clicked.   It looks like this...

                function processInfo()
                {
                        // JavaScript code goes here
                }
        

3.      The last function should be triggered when the browser window   
        fully loads.  It should assign the processInfo function to 
        run when the button is clicked.
        
        
                window.onload = function ()
                {
                        $("mybutton").onclick = processInfo;  //Remember do not use ()!!
                }
                
                

Solutions

Expert Solution

Note: Done accordingly. Please comment for any problem. Please Uprate. Thanks.

Code:

<!DOCTYPE html>
<html>
<body>

<h2>Javascript Validation</h2>
First name: <input type="text" name="fname" id="fname"><br>
<br>
Last name: <input type="text" name="lname" id="lname">
<br>
<br>
Number of Pets: <input type="number" name="totalPets" id="totalPets" onchange="openInputs()">
<br>
<div id="error" style="color:red;"></div>
<br>
First Pet name: <input type="text" name="pet1" id="pet1" disabled><br>
<br>
Second Pet name: <input type="text" name="pet2" id="pet2" disabled>
<br>
<br>
Third Pet name: <input type="text" name="pet3" id="pet3" disabled><br>
<br>
<button type="button" id="mybutton">Process...</button>

<script>
window.onload = function ()
{
$("mybutton").onclick = processInfo; //Remember do not use ()!!
}
function openInputs(){
totalPets=$("totalPets").value;
for(counter=1; counter<=3; counter++)
{
myPetId = 'pet' + counter;
$(myPetId).value="";
myPetName = $(myPetId).disabled=true;
  
}
for(counter=1; counter<=totalPets; counter++)
{
myPetId = 'pet' + counter;
myPetName = $(myPetId).disabled=false;
}
}
var $ = function (id) {
return document.getElementById(id);
}
function processInfo()
{
var errorFoundFlag = 'N'; //Initialize variable to 'N'
firstName=$("fname").value;
lastName=$("lname").value;
totalPets=$("totalPets").value;
var msg="";
var letters = /^[A-Za-z]+$/;
if (firstName=="")
{
msg += "First Name should not be empty <br>";
errorFoundFlag = 'Y';
}else{
if (!firstName.match(letters))
{
msg += "First Name should be alphabetical only <br>";
errorFoundFlag = 'Y';
}
}

if (lastName=="")
{
msg += "Last Name should not be empty <br>";
errorFoundFlag = 'Y';
}else{
if (!lastName.match(letters))
{
msg += "Last Name should be alphabetical only <br>";
errorFoundFlag = 'Y';
}
}
if (totalPets=="")
{
msg += "Pet Number should not be empty <br>";
errorFoundFlag = 'Y';
}
  
if (totalPets<0 || totalPets>3)
{
msg += "Pet Number should be between 0-3 <br>";
errorFoundFlag = 'Y';
}

if (errorFoundFlag == 'N')
{
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!

var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var name=lastName+","+firstName;
var today = mm + '-' + dd + '-' + yyyy;
var pets="";
for(counter=1; counter<=totalPets; counter++)
{
myPetId = 'pet' + counter;
myPetName = $(myPetId).value;
pets=pets+"Pet"+counter+" :"+myPetName+"\n";
}
alert(name+"\n"+today+"\n"+pets);
}else{
                   $("error").innerHTML=msg;
//alert("Errors found :\n"+msg);
}
}
  
</script>

</body>
</html>


Related Solutions

Need to HAVE a web page that uses a loop to allow a teacher to enter...
Need to HAVE a web page that uses a loop to allow a teacher to enter the following information for all students in a class: student's name, mt  grade, f  grade, hW grade, attendance grade. program should calculate each student's numeric total grade based on the following formula:course grade = (mT*0.3)+(f*0.4)+(homework*0.2)+(attendance*0.1)File Table.html looks like this:When the button is clicked, you need to prompt the user the following information:-number of students (which will determine the number of rows in your table)-student's name-mT grade-f...
For this assignment you are required to create a web page displaying a recipe of your...
For this assignment you are required to create a web page displaying a recipe of your choosing. Your submission should appropriately use the basic head and body construction of an HTML document. Additionally you are required to appropriately use at least three different HTML element types. For example you might use an unordered list for your ingredients, an ordered list for the steps of your recipe, and an image to show the final result. If you choose to use an...
In this weeks assignment you will creating some character cards on a web page. These character...
In this weeks assignment you will creating some character cards on a web page. These character cards can be similar to a baseball card, Magic The Gathering Card. It is your choice and anything is fair game. Requirements: Use an external CSS & JS file, no internal or inline styles & scripts Please comment your JS to break down your understanding of what is happening. Please put your name in your code. Create at least 3 character card elements (div's...
In this assignment you will create a web page about your favorite sports to play or...
In this assignment you will create a web page about your favorite sports to play or teams to watch. If you don’t watch or play sports, please make up your favorite sports to play or teams to watch. You will be incorporating images into your web page, as well as other concepts learned in this unit. Create an external style sheet using a text editor of your choosing. In the CSS file add the following style rules: A background image...
1 -​Create the code to generate a default web page. The contents of this page should...
1 -​Create the code to generate a default web page. The contents of this page should be Your​​Name, right justified
C++ code Inventory Item Stack You are writing an Inventory program that will allow the user...
C++ code Inventory Item Stack You are writing an Inventory program that will allow the user to enter a part into the inventory, take a part from the inventory, or quit. You are provided with the InvItem class (InvItem.h) and a partial Driver.cpp. You will be creating a DynamicStack class that should implement a Stack data structure. The DynamicClass should be implemented as a template class to allow any data type be added/removed from the stack. You will submit three...
CODE IN PYTHON: Your task is to write a simple program that would allow a user...
CODE IN PYTHON: Your task is to write a simple program that would allow a user to compute the cost of a road trip with a car. User will enter the total distance to be traveled in miles along with the miles per gallon (MPG) information of the car he drives and the per gallon cost of gas. Using these 3 pieces of information you can compute the gas cost of the trip. User will also enter the number of...
Develop the pseudo code for, desk check and test the following programs. Allow the user to...
Develop the pseudo code for, desk check and test the following programs. Allow the user to provide the number of elements, and initialise the array according to their input. Use functions where appropriate to ensure modularity. 1. Find the average of a list of numbers 2. Find the smallest element in a list of numbers
Write the XHTML code for a short Web page. Include the following along with the usual...
Write the XHTML code for a short Web page. Include the following along with the usual HTML and BODY tags. You can use whatever hyperlinks and image URLs you want. (other than distasteful sites, that is!) A title Email link A graphic (gif or jpg) Hyperlink(s) to other sites. Heading A list (can be unnumbered, numbered, etc…) A background color or a background image. please do not copy the previous answer.
Write the XHTML code for a short Web page. Include the following along with the usual...
Write the XHTML code for a short Web page. Include the following along with the usual HTML and BODY tags. You can use whatever hyperlinks and image URLs you want. (other than distasteful sites, that is!) A title Email link A graphic (gif or jpg) Hyperlink(s) to other sites. Heading A list (can be unnumbered, numbered, etc...) A background color or a background image.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT