www.webdeveloper.com
Results 1 to 3 of 3

Thread: Problems/errors when validating/displaying items from an associative array

  1. #1
    Join Date
    Jul 2009
    Posts
    2

    Unhappy Problems/errors when validating/displaying items from an associative array

    Hi all ---

    My problem is that I am meant to write a "shopping cart" kind of code that will:

    1) Create an associative array that stores a few items and their prices (i.e. Webcam is $50 and printer is $99).
    2) Create a loop that displays each item and its price in input boxes on the page, plus a box for users to enter a quantity into
    3) When the users hit submit, it needs to perform a function
    4) A new associative array is created, and, the code needs to use a loop to test for a submit button, check to see if there is something in the Qty input box then change quantities into numbers
    5) Display the contents of the associative array on screen

    If I entered a quantity of 2 for the Webcam and 1 for the Printer, it should result in something like:
    "You have purchased the following items:
    Webcam at a cost of $100
    Printer at a cost of $99"

    However, the code I use to check for input in the Qty box malfunctions and seems to result in a blank for every single box there, even if there is already a value in there.

    Also, it continues on to the dummy display code even though it failed the test. It is meant to stop if it encounters an error.

    It sounds very simple, but I am obviously just Not Getting It unfortunately, as I've had no end of trouble and the nagging feeling that this textbook is very out of date.

    I am a complete amateur at writing code, and have run into so many errors, dodgy self-written codes, general FAILURE on my part due to my own incompetence and lack of understanding of Javascript, that I am about ready to tear my hair out in frustration.

    I am not a programmer, I barely understand what I'm doing, yet Javascript is part of a course I am doing and thus I have no choice.

    I have searched the Internet and I searched these (and other forums) and found things that were oh-so-close but no cigar. I found very very simplistic examples of bits of what I want to do, but I just don't have the understanding of this to make the leaps in logic it requires to apply it to my code. I have been working on this one code for over a week and am astonished I managed to get this far.

    If some kind soul out there could please look over my code (below) and at least give me some hint of where I've gone wrong, I would be eternally grateful. This is actually for an assignment that is due tomorrow, so if anyone happens to see and respond to this before then, FANTASTIC, but if not, I will just deal and/or try for an extension. Either way I would dearly love some help with this:

    Code:
    <script language="Javascript" type="text/javascript">
    
    // Create a new form and table
    document.write("<form name='productform'><br><table name='prodtable' width='300'>");
    
    // Declare variables and new array
    var Products = new Array();
    Products["Webcam"] = "50.00";
    Products["Printer"] = "99.00";
    
    // Create field headings for the form
    document.write("<tr><td>Item</td><td>Price</td><td>Your Quantity</td></tr>");
    
    // Create For loop that will display product name and price in text fields
    for (var Item in Products)
    	{
    		document.write("<tr><td><input disabled=true type='text' name= '" + Item + "' id='" + Item + "' value='" + Item + "'></td>");
    		document.write("<td><input disabled=true type='text' name='" + Products[Item] + "' id='" + Products[Item] + "' value=" + Products[Item] + "></td>");
    		document.write("<td><input type='text' name='Qty' id='Qty'></td></tr>"); 
    	}
    
    document.write("<tr><td></td><td><input type='submit', value='Submit Sale', onClick='DisplayItems();'></td><td></td></tr>");
    document.write("</table>");
    document.write("</form>");
    
    
    // Begin function to display items
    function DisplayItems()
    {
    
    var SaleItems = new Array();
    var ItemName;
    var Price;
    var Qty;
    
    var count = 0;
    var element;
    
    element = document.getElementsByTagName('input');
    
    for (count = 0; count<element.length; count++)
        {
    		switch (element[count].type)
    			{
    				case "submit":
    				break;
    				
    				default:
    				if (!(element[count + 2].value.length==0))
    					{
    					alert("You need to enter a number into " + element[count+2].name);
    	
    					ItemName=element[count];
    					Price=element[count + 1];
    					Qty=element[count + 2];	
    					
    					SaleItems[ItemName] = parseFloat(Price) * parseFloat(Qty);
    					
    					}
    	
        		}
       
    	}
    
    // Code to display the items and their total price (unfinished)
    for (ItemName in SaleItems)
        {
                
                document.write("This is the display dummy code " + ItemName + " and " + SaleItems[ItemName]);
                
        }
    
    }
    
    
    </script>
    Please let me know if I've left out any necessary info. I tried to be as descriptive with my problems as possible.

    Thank you in advance

  2. #2
    Join Date
    Jun 2004
    Location
    Portsmouth UK
    Posts
    2,689
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
      <title></title>
    </head>
    
    <body>
    <script language="Javascript" type="text/javascript">
    
    // Create a new form and table
    document.write("<form name='productform'><br><table name='prodtable' width='300'>");
    
    // Declare variables and new array
    var Products = new Array();
    Products["Webcam"] = "50.00";
    Products["Printer"] = "99.00";
    
    // Create field headings for the form
    document.write("<tr><td>Item</td><td>Price</td><td>Your Quantity</td></tr>");
    
    // Create For loop that will display product name and price in text fields
    for (var Item in Products)
    	{
    		document.write("<tr><td><input disabled=true type='text' name= '" + Item + "' id='" + Item + "' value='" + Item + "'></td>");
    		document.write("<td><input disabled=true type='text' name='" + Products[Item] + "' id='" + Products[Item] + "' value=" + Products[Item] + "></td>");
    		document.write("<td><input type='text' name='Qty' id='Qty'></td></tr>");
    	}
    
    document.write("<tr><td></td><td><input type='button', value='Submit Sale', onClick='DisplayItems();'></td><td></td></tr>");
    document.write("</table>");
    document.write("</form>");
    
    
    // Begin function to display items
    function DisplayItems()
    {
    
    var SaleItems = new Array();
    var ItemName;
    var Price;
    var Qty;
    
    var count = 0;
    var element;
    
    var qty = document.getElementsByName('Qty');
      for (var tr,ips,z0=0;z0<qty.length;z0++){
       qty[z0].value=qty[z0].value.replace(/\D/g,''); // only digits
       if (qty[z0].value&&qty[z0].value>0){
        qty[z0].value=parseInt(qty[z0].value); // only integers
        tr=qty[z0];
        while (tr.nodeName!='TR'){  // find the parent TR
         tr=tr.parentNode;
        }
        ips=tr.getElementsByTagName('INPUT');// the inputs in the TR
        if (ips) SaleItems.push([ips[2].value+' of ' +ips[0].value+' total '+ips[1].value*ips[2].value])
       }
      }
      document.getElementById('display').innerHTML=SaleItems.join('<br>');
    }
    
    </script>
    <div id="display" ></div>
    </body>
    
    </html>
    Vic

    God loves you and will never love you less.

    http://www.vicsjavascripts.org/Home.htm
    If my post has been useful please donate to http://www.operationsmile.org.uk/

  3. #3
    Join Date
    Jul 2009
    Posts
    2
    Quote Originally Posted by imaliea View Post
    Hi all ---

    My problem is that I am meant to write a "shopping cart" kind of code that will:

    1) Create an associative array that stores a few items and their prices (i.e. Webcam is $50 and printer is $99).
    2) Create a loop that displays each item and its price in input boxes on the page, plus a box for users to enter a quantity into
    3) When the users hit submit, it needs to perform a function
    4) A new associative array is created, and, the code needs to use a loop to test for a submit button, check to see if there is something in the Qty input box then change quantities into numbers
    5) Display the contents of the associative array on screen

    If I entered a quantity of 2 for the Webcam and 1 for the Printer, it should result in something like:
    "You have purchased the following items:
    Webcam at a cost of $100
    Printer at a cost of $99"

    However, the code I use to check for input in the Qty box malfunctions and seems to result in a blank for every single box there, even if there is already a value in there.

    Also, it continues on to the dummy display code even though it failed the test. It is meant to stop if it encounters an error.

    It sounds very simple, but I am obviously just Not Getting It unfortunately, as I've had no end of trouble and the nagging feeling that this textbook is very out of date.

    I am a complete amateur at writing code, and have run into so many errors, dodgy self-written codes, general FAILURE on my part due to my own incompetence and lack of understanding of Javascript, that I am about ready to tear my hair out in frustration.

    I am not a programmer, I barely understand what I'm doing, yet Javascript is part of a course I am doing and thus I have no choice.

    I have searched the Internet and I searched these (and other forums) and found things that were oh-so-close but no cigar. I found very very simplistic examples of bits of what I want to do, but I just don't have the understanding of this to make the leaps in logic it requires to apply it to my code. I have been working on this one code for over a week and am astonished I managed to get this far.

    If some kind soul out there could please look over my code (below) and at least give me some hint of where I've gone wrong, I would be eternally grateful. This is actually for an assignment that is due tomorrow, so if anyone happens to see and respond to this before then, FANTASTIC, but if not, I will just deal and/or try for an extension. Either way I would dearly love some help with this:

    Code:
    <script language="Javascript" type="text/javascript">
    
    // Create a new form and table
    document.write("<form name='productform'><br><table name='prodtable' width='300'>");
    
    // Declare variables and new array
    var Products = new Array();
    Products["Webcam"] = "50.00";
    Products["Printer"] = "99.00";
    
    // Create field headings for the form
    document.write("<tr><td>Item</td><td>Price</td><td>Your Quantity</td></tr>");
    
    // Create For loop that will display product name and price in text fields
    for (var Item in Products)
    	{
    		document.write("<tr><td><input disabled=true type='text' name= '" + Item + "' id='" + Item + "' value='" + Item + "'></td>");
    		document.write("<td><input disabled=true type='text' name='" + Products[Item] + "' id='" + Products[Item] + "' value=" + Products[Item] + "></td>");
    		document.write("<td><input type='text' name='Qty' id='Qty'></td></tr>"); 
    	}
    
    document.write("<tr><td></td><td><input type='submit', value='Submit Sale', onClick='DisplayItems();'></td><td></td></tr>");
    document.write("</table>");
    document.write("</form>");
    
    
    // Begin function to display items
    function DisplayItems()
    {
    
    var SaleItems = new Array();
    var ItemName;
    var Price;
    var Qty;
    
    var count = 0;
    var element;
    
    element = document.getElementsByTagName('input');
    
    for (count = 0; count<element.length; count++)
        {
    		switch (element[count].type)
    			{
    				case "submit":
    				break;
    				
    				default:
    				if (!(element[count + 2].value.length==0))
    					{
    					alert("You need to enter a number into " + element[count+2].name);
    	
    					ItemName=element[count];
    					Price=element[count + 1];
    					Qty=element[count + 2];	
    					
    					SaleItems[ItemName] = parseFloat(Price) * parseFloat(Qty);
    					
    					}
    	
        		}
       
    	}
    
    // Code to display the items and their total price (unfinished)
    for (ItemName in SaleItems)
        {
                
                document.write("This is the display dummy code " + ItemName + " and " + SaleItems[ItemName]);
                
        }
    
    }
    
    
    </script>
    Please let me know if I've left out any necessary info. I tried to be as descriptive with my problems as possible.

    Thank you in advance
    This worked amazingly well ---- much better than what the textbook code was trying to get me do! Thank you so much! You're brilliant

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles