www.webdeveloper.com
Results 1 to 15 of 15

Thread: Basket Help

  1. #1
    Join Date
    May 2010
    Posts
    8

    Basket Help

    I have a problem with my shopping cart. This is my first time using JavaScript so I am a beginner and there may be some things that I have not understood properly.

    What I am trying to achieve is this: I want button where I can add my item to the shopping cart e.g AddToCart() so I can add my items with the number of quantities that the person will want. To do this I need global arrays like sum, quanitity and name. Except the way I have done it does not have this and I'm not sure how implement this.

    The hint that was given to me is this: The price and name of each toy should be read directly from the web page using the DOM method call document.getElementByID(itemPriceID-or-itemNameID).innerHTML, where itempriceID and itemNameID are the idís of the HTML elements which display the price and name of each toy. (Note: the price (read directly from the page) will be of type string, this needs to be converted to a number, so in order to perform type you will need to use the Javascript type conversion method parseFloat(price) )).

    I then need a ViewShoppingCart() which will make a loop through the arrays and display it in a table with the total sum. What I have done is a bit similar but my knowledge and experience was not enough to accomplish the above problem. I hope this makes more sense.
    (I have a feeling the code I have so far is wrong)
    Code:
    var productname = new array();
    var productprice = new array();
    var productquantity = new array();
    function cart()
      {
      for (i=1;i<=3;i++)
        {
        var name = 'title'+i;
        var price = 'price'+i;
        var quantity = 'qty'+i;
        productname[i] = document.getElementById(name).innerHTML;
        productprice[i] = document.getElementById(price).innerHTML;
        var selectfield = document.getElementById(quantity).
        productquantity[i] = selectfield.options[selectfield.selectedIndex].text;
        }
      }  
    checkvalue=parseFloat(price);
    I know I need to quantity into integer, price into float and do the calculations you plan to do. So total price would be productprice[1] + productprice[2] + productprice[3]. But I am now stuck and don't know how to continue. If someone could guide me or give me some hints that would be very helpful.

  2. #2
    Join Date
    Oct 2006
    Posts
    939
    Could you provide a sample of HTML including the buttons and the
    document.getElementByID(itemPriceID-or-itemNameID).innerHTML

    No need to give us meta tags and the rest of the nine yards, we only need to
    see what you want to work with.

  3. #3
    Join Date
    Aug 2007
    Posts
    3,767
    Code:
    var productname = new Array();
    // OR
    var productname = [];
    They are the same thing.

  4. #4
    Join Date
    May 2010
    Posts
    8
    This is my HTML code, with the buttons and an item.
    Code:
     <div id="product3">
     <p id="title3"><b>xbox</b></p>
     <img src="../images/xbox.jpg" /><p id="price3">price &#163;149.99</p> <b>Qty</b>
     <select name="qty3">
       <option value="number">0</option>
       <option value="number">1</option>
       <option value="number">2</option>
       <option value="number">3</option>
       <option value="number">4</option>
       <option value="number">5</option>
     </select>
     </div> 
     <br />
     <input type="button"name="button1"value="Add to cart"onclick="calculate cart()"; />
    As I was working with the javascript I added this code underneath the current one, but I don't know what I'm doing 100&#37;
    Code:
    function addtocart(id) {
    productname = document.getElementById('name' + id).innerHTML;
    productquantity = parseInt(document.getElementById('qty' + id).value);
    productqrice = parseFloat(document.getElementById('price' + id).innerHTML);
    if(numitems == 0){	
    items[++numitems] = new Item(itemName,itemPrice,itemQuantity);
    displaycart();
    }
    else{
    checkarray(id, productname, productquantity, productprice);
    }

  5. #5
    Join Date
    Oct 2006
    Posts
    939
    I don't know why but, my brain always gets hiJacked demanding to do it it's way or no way.
    var M should be- var M='& # 1 6 3 ; '; (remove spaces)

    HTML Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    	"http://www.w3.org/TR/html4/strict.dtd">
    <HTML>
    <HEAD><TITLE>shopping</TITLE>
    <META http-equiv=Content-Type content="text/html; charset=UTF-8">
    <STYLE type=text/CSS>
    fieldset{width:300px}
    legend{font-size:24px;font-family:comic sans ms;color:#004455}
    </STYLE>
    
    <META content="MSHTML 6.00.2900.2963" name=GENERATOR></HEAD>
    <BODY scroll="auto">
    <div id="products"></div><hr>
    <div id="inCart"></div>
    
    <SCRIPT type="text/javascript">
    var items=['Xbox~149.99','StuffedGizmo~19.98','GadgetyGoop~9.97'];
    
    var M='£';		var product=[]; var price=[];	var stuff='';
    
    function wpf(product,price){var pf='<form><FIELDSET><LEGEND>'+product+'</LEGEND>';
    		pf+='<img src="../images/'+product+'.jpg"  alt="'+product+'" ><p>price '+M+''+price+'</p> <b>Qty</b><SELECT>';
    	for(i=0;i<6;i++){pf+='<option value="'+i+'">'+i+'</option>'}	pf+='</SELECT>';
    	 pf+='<input type="button" value="Add to cart" onclick="cart()" /></FIELDSET></form>';
    	return pf
    }
    
    	for(j=0;j<items.length;j++){
    		product[j]=items[j].substring(0,items[j].indexOf('~'));
    		price[j]=items[j].substring(items[j].indexOf('~')+1,items[j].length);
    		stuff+=''+wpf(product[j],price[j])+'';
    	}
    document.getElementById('products').innerHTML=stuff;
    
    function cart(){ var order=[]; var tot=0
    	for(o=0,k=0;o<document.forms.length;o++){
    		 if(document.forms[o].elements[1].value!=0){
    			qnty=document.forms[o].elements[1].value;
    			order[k]=''+product[o]+'_'+qnty+'*'+price[o]+'';
    			tot+=qnty*price[o];k++
    		}
    	}
    
    document.getElementById('inCart').innerHTML=order.join('<br>')+'<h3>Total '+tot+'</h3>';
    }
    
    </SCRIPT>
    </BODY></HTML>

  6. #6
    Join Date
    May 2010
    Posts
    8
    Ah Thankyou very much, it works now
    Also is there a way to structure the javascript so that I have 2 buttons where one just adds to cart, but then there is a button where I can then view the shopping cart?
    I have something I found and I'm trying to add it but I don't know what going on here.
    Code:
    function viewcart()
    {
      var total = 0;
      var i = 0;
      with (top.main.document)
      {
        write();
        close();
        write("<HTML><TITLE>Shopping Cart</TITLE>");
        write("<BODY BGCOLOR=antiquewhite><CENTER>");
        write("<H2>Thank you for your order</H2>");
        write("<TABLE BORDER=1 CELLPADDING=3 CELLSPACING=1 WIDTH=500>");
        for (i in cart)
        {
          total = total + cart[i].price;
          if (cart[i].itemcnt != null);
          {
            cart[i].display(top.main.document);
          }
        }
        write("<TR><TD>Total = </TD><TD ALIGN=RIGHT>$" + total + "</TD>");
        write("<TD>&nbsp;</TD></TR></TABLE><BR>");
        write("</CENTER></BODY></HTML>");
      }
    }
     
    </SCRIPT>
    </HTML>

    And then I guess I am going to need something like
    Code:
    "JavaScript:top.hidden.viewcart()">View Order
    Am I doing this right?

  7. #7
    Join Date
    Oct 2006
    Posts
    939
    That looks fairly sophisticated. Seems you would know what you are doing if you wrote any of it?

  8. #8
    Join Date
    May 2010
    Posts
    8
    No I didn't write that, it's a code I found in a tutorial for shopping cart, I'm just trying to implement it that's all

  9. #9
    Join Date
    May 2010
    Posts
    8
    @justinbarneskin:
    In your javascript you've done it so it has the html (images and such) in with the javascript. Is there a way that I can separate it?, because I want a separate .js file that will be linked to my .html file.

  10. #10
    Join Date
    Oct 2006
    Posts
    939
    I'm fairly lost now. You might discover that, many of your projects will not only get edited
    but, you might decide to rewrite them totally from scratch. What have you so far?

  11. #11
    Join Date
    May 2010
    Posts
    8
    I'll try explaining it better. Basically This is what I have so far, I've just changed one thing from the code you provided. which is the submit button that I have put outside the script
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    	"http://www.w3.org/TR/html4/strict.dtd">
    <HTML>
    <HEAD><TITLE>shopping</TITLE>
    <META http-equiv=Content-Type content="text/html; charset=UTF-8">
    <STYLE type=text/CSS>
    fieldset{width:300px}
    legend{font-size:24px;font-family:comic sans ms;color:#004455}
    </STYLE>
    
    <META content="MSHTML 6.00.2900.2963" name=GENERATOR></HEAD>
    <BODY scroll="auto">
    <div id="products"></div><hr>
    <div id="inCart"></div>
    
    <SCRIPT type="text/javascript">
    var items=['Xbox~149.99','StuffedGizmo~19.98','GadgetyGoop~9.97'];
    
    var M='�';		var product=[]; var price=[];	var stuff='';
    
    function wpf(product,price){var pf='<form><FIELDSET><LEGEND>'+product+'</LEGEND>';
    		pf+='<img src="../images/'+product+'.jpg"  alt="'+product+'" ><p>price '+M+''+price+'</p> <b>Qty</b><SELECT>';
    	for(i=0;i<6;i++){pf+='<option value="'+i+'">'+i+'</option>'}	pf+='</SELECT>';
    	 pf+='<input type="button" value="Add to cart" onclick="cart()" /></FIELDSET></form>';
    	return pf
    }
    
    	for(j=0;j<items.length;j++){
    		product[j]=items[j].substring(0,items[j].indexOf('~'));
    		price[j]=items[j].substring(items[j].indexOf('~')+1,items[j].length);
    		stuff+=''+wpf(product[j],price[j])+'';
    	}
    document.getElementById('products').innerHTML=stuff;
    
    function cart(){ var order=[]; var tot=0
    	for(o=0,k=0;o<document.forms.length;o++){
    		 if(document.forms[o].elements[1].value!=0){
    			qnty=document.forms[o].elements[1].value;
    			order[k]=''+product[o]+'_'+qnty+'*'+price[o]+'';
    			tot+=qnty*price[o];k++
    		}
    	}
    
    document.getElementById('inCart').innerHTML=order.join('<br>')+'<h3>Total '+tot+'</h3>';
    }
    
    </SCRIPT>
    <input type="button" value="Add to cart" onclick="cart()" /></FIELDSET></form>
    </BODY></HTML>
    But what I am trying to do is make 2 files: one HTML file and one Javascript file, so that it will be linked to each other. Like so
    Code:
    <script type="text/javascript" src="shoppingcart.js" /> 
    	</script>
    But its not working because the images and fieldset are in the javascript and I want to separate them.

    So the HTML would be like this
    Code:
    <form name="form1" method="post" action="data.php" >
     <div id="product1">     
     <p id="title1"><b>Star Wars Tie Interceptor</b></p>
     <img src="../Assingment Pics/Tie Interceptor.jpg" /> <p id="price1">Price £39.99</p> <p><b>Qty</b></p>
       <select name="qty">
         <option value="number">0</option>
         <option value="number">1</option>
         <option value="number">2</option>
         <option value="number">3</option>
         <option value="number">4</option>
         <option value="number">5</option>
        </select> 
     </div>
    <div id="product2">
     <p id="title2"><b>Star Wars Clone Wars Vehicles Corporate Allinace Tank</b></p>
     <img src="../Assingment Pics/Corporate Tank.jpg" /><p id="price2">Price £29.99</p> <b> Qty</b>
     <select name="qty2">
       <option value="number">0</option>
       <option value="number">1</option>
       <option value="number">2</option>
       <option value="number">3</option>
       <option value="number">4</option>
       <option value="number">5</option>
        </select>
    </div>
    <input type="button" value="Add to cart" onclick="cart()" /></FIELDSET></form>
    and then there would be another javascript file with only the javascript.
    Does that make sense?

  12. #12
    Join Date
    Oct 2006
    Posts
    939
    Here we go...
    1. You need to have unique values in the select options.


    1. You cannot change the layout of your HTML as it is written, the script is digging out the stuff it needs and if you change the HTML, the script will fail


    Here is the html-
    HTML Code:
    <form name="form1" method="post" action="data.php" >
     <div id="product1">     
     <p id="title1"><b>Star Wars Tie Interceptor</b></p>
     <img src="../Assingment Pics/Tie Interceptor.jpg" /> <p id="price1">Price £39.99</p> <p><b>Qty</b></p>
       <select name="qty">
         <option value="0">0</option>
         <option value="1">1</option>
         <option value="2">2</option>
         <option value="3">3</option>
         <option value="4">4</option>
         <option value="5">5</option>
        </select> <input type="button" value="Add to cart" onclick="cart()" />
     </div>
    <div id="product2">
     <p id="title2"><b>Star Wars Clone Wars Vehicles Corporate Allinace Tank</b></p>
     <img src="../Assingment Pics/Corporate Tank.jpg" /><p id="price2">Price £29.99</p> <p><b>Qty</b></p>
     <select name="qty2">
       <option value="0">0</option>
       <option value="1">1</option>
       <option value="2">2</option>
       <option value="3">3</option>
       <option value="4">4</option>
       <option value="5">5</option>
        </select> <input type="button" value="Add to cart" onclick="cart()" />
    </div>
    </form>
    and here is the remote script you call with
    <script type="text/javascript" src="shoppingcart.js" /></script>

    HTML Code:
    var f,d,str,items,qnts,price,bag,total;	
    
    function cart(){ f=document.forms[0];	d=f.getElementsByTagName('div'); var items=[];var qnts=[];price=[];bag=[]
    	for(i=0,e=0;i<d.length;i++){	
    					items[i]=d[i].getElementsByTagName('b')[0].innerHTML;
    					qnts[i]=d[i].getElementsByTagName('select')[0].value;
    					str=d[i].getElementsByTagName('p')[1].innerHTML;
    					priceStart(str,i);	
    	if(qnts[i]!=0){bag.push(new Array());	ib=bag[bag.length-1];
    	ib.push(items[i]);ib.push(qnts[i]);ib.push(price[i]);ib.push(qnts[i]*price[i]);}
    	}
       if(bag.length>0){
        total=bag[0][3]; if(bag.length>1){for(t=1;t<bag.length;t++){total+=bag[t][3]}}
        alert(bag.join('\n')+'\n----------------\ntotal='+total)
       }
    }
    function priceStart(str,inx){for(j=0;j<str.length;j++){if(str.charAt(j)!=' ' && !isNaN(str.charAt(j))){priceEnd(j,str,inx);return }}}
    function priceEnd(j,str,inx){for(k=str.length;k>j;k--){if(str.charAt(k)!=' ' && !isNaN(str.charAt(k))){price[inx]=str.substring(j,k);return }}}

  13. #13
    Join Date
    May 2010
    Posts
    8
    hmmm I tried that code but when I click add to cart nothing happens? I've linked it.
    EDIT: its working now thanks , btw is there a way I can add a view function cart? so I can view the the information and total in a table on the same page?
    Last edited by shadowplayer; 05-08-2010 at 07:20 AM.

  14. #14
    Join Date
    Oct 2006
    Posts
    939
    Its this line here to work-
    HTML Code:
    alert(bag.join('\n')+'\n----------------\ntotal='+total)
    either compile it into something that can be used for innerHTML
    or more complex, to open and write a new window.

  15. #15
    Join Date
    May 2010
    Posts
    8
    ok thanks for all the help

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