Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could possible use an object (which are similar to HashMaps in other programming languages, or also associative arrays) to store the current cart state and act on future clicks after inspecting this object. You would also need to keep track of current number of products as this is not provided by JavaScript objects. It's up to you what you would store as the value </p> <p>//Initially empty, or you could initialize it to the saved cart state. var cartProducts = {}, numProducts = 0;</p> <p>$("#addCart").click(function () {</p> <pre><code>if (numProducts === 0) { //Here, create the DOM fragment representing your product. cartProducts["product-id"] = $("&lt;div"); numProducts += 1; } else if(cartProducts["product-id"]) { //Update the product price since it has already been added to the DOM. //When refactoring, combine this else statement with the first if condition. } else { //At this point you know that the product has not been previously add it, //and can go ahead and add it to the DOM. //... numProducts += 1; } </code></pre> <p>});</p> <p>Just <strong>general comments</strong> on your code structure:</p> <ol> <li>Commenting your code would help others and you in the future to understand your code. </li> <li>Try to modularize your code into separate functions that are responsible for a small chunks of code. This will help with the code manageability, reuseability, and testability. </li> <li>Use for loops instead of while loops if you are going to iterate [i->n; i++].</li> <li><a href="http://www.jslint.com/" rel="nofollow">JSLint</a> your code to help you with styling and proper syntax. </li> </ol> <p>Hope this helps you out! </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload