Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Tadjiev Codes
Tadjiev Codes
9,626 Points

JS project related issues

Dea Treehouse members,

Could someone help to fix the last two things in my project? Everything seems to be ready besides two things.

1)In addToCart() function, when I add the same item, It creates a new item in the Cart instead of incrementing.

        if (points === 4 && cartItems.find(p => p.productId === cartItems.productId)) {
            productId.quantity++;
        } else {
            alert("Successful incremented purchase of the Timepiece");
            cartItems.push(new cartItem(itemID, obj[0].price, quantityCart, obj[0].costOfShipping));
        }
     ```

 I tried many ways but doesn't work.
2)My reviewItem() function displays the entry of the review and outputs on the div.
Then, I try to push it inside the array of reviews, which is stored inside the storeItems array.


```js

storeItems[i].reviews.push(reviewIdInput);

my groupmate told me that this push works for him. Maybe sth wrong with my arrays data with backticks? Logically this should push it into the array. When I click item details button. I want to see the updated entered review.

Workspace: https://w.trhou.se/yrmv7pbs8l

I'm really sorry to disturb you again Mr.Steven Steven Parker (

I tried my best to solve these issues but I'm running out of time now. Tomorrow 24 night Is my deadline for submission.

Could you please help me to quickly fix the issues like what code to write to fix these issues? I think you've got an eye for finding out small errors. I'm not going to disturb you anymore for a few weeks. This is the end of the semester tomorrowπŸ™πŸ™πŸ™

7 Answers

Steven Parker
Steven Parker
231,271 Points

Zimri has the right idea, if "cartItems" is the array, then it would not have a "productId" attribute. Based on what would otherwise be pushed, that should just be "itemID" instead. And that "alert" seems to be in the wrong code block.

So I've been doing your homework? :speak_no_evil:

Tadjiev Codes
Tadjiev Codes
9,626 Points
function reviewItem() {



        //let reviewIdInput = document.getElementById('reviewIdMessage').value;
        var reviewDisplay = document.getElementById('reviewId').value;
        var reviewDisplaying = document.getElementById('reviewId');
        let reviewIdInput = document.getElementById('reviewDesc').value;


        for (var i = 0; i < storeItems.length; i++) {
            // check for match

            if (storeItems[i].productId == reviewDisplay) {
                storeItems[i].reviews.push(reviewIdInput);

                alert(`Successful entry of the Review, Thank you!
                          ${reviewIdInput}`);
                // Output nearby doesn't work or works?
                reviewDisplaying.innerHTML += `Latest Review: ${reviewIdInput}`;
            }

        } // loop end 

    } // function end 

I actually solved the Review problem now it finally pushes the review and displays in item details. The only thing now the output code " reviewDisplaying.innerHTML += Latest Review: ${reviewIdInput}; " doesn't work. Yes, but some of the small projects were just exercises for each covered new topic. But you really helped me out a lot of times when I was stuck and hating myself that I'm so stupid πŸ™ Thankful to have such amazing people like you who can help out Steven Parker πŸ™πŸ™πŸ™

if (points === 4 && cartItems.find(p => p.productId === cartItems.productId))

what are you trying to compare the p.productId to?

Tadjiev Codes
Tadjiev Codes
9,626 Points

If productId that's already in the cart, then I want the same item in the cart to be incremented. Instead of creating a new Item in the cart.

what did you name the product id?

Because you're now looping through the cartItems ('p' represents a product in the cart) and comparing the ids of those products in the cart to cartItems.productId.

cartItems.productId should be something else, but what exactly that's called, I can't tell without knowing the variable you want to compare it to.

Tadjiev Codes
Tadjiev Codes
9,626 Points

I named it :productId in the function constructor of cartItems

var itemID = document.getElementById("addItemId").value;

This is the name of the variable for the input textbox where I get the value

function cartItem(productId, price, quantity, shipping) {
        this.productId = productId; // String the id of the product
        this.price = price; // Float – the price of the item
        this.quantity = quantity; // Int – the amount of this product in the cart
        this.shipping = shipping; // Float – cost of shipping for this item
    }

    // Global Empty Arrays to contain our objects of Store Items and Cart Items that will be created through the constructor
    let storeItems = [];
    let cartItems = []; 
Tadjiev Codes
Tadjiev Codes
9,626 Points
        if (points === 4 && cartItems.find(p => p.productId === itemID)) {
            productId.quantity++;
            alert("Successful incremented purchase of the Timepiece");
        } else {
            cartItems.push(new cartItem(itemID, obj[0].price, quantityCart, obj[0].costOfShipping));
        } 

Still trying to solve this. Now it adds the first item but never adds the second item at all. Sth is wrong with the logic or I dunno ...

Tadjiev Codes
Tadjiev Codes
9,626 Points

Any solutions for this conditional? I'm afraid I'll have to rewrite a lot of functions to make this work

Steven Parker
Steven Parker
231,271 Points

The conditional is fine, but "productId" is not a thing by itself. It's a property of the "cartItem" class.

You should see this kind of error in the console log, which I assume you are using since you have explicit log statements in your code. When this error occurs, the console displays:

project.js:691 Uncaught ReferenceError: productId is not defined :point_left:
  at addToCart (project.js:691)
  at HTMLInputElement.onclick (store.html:130)

Tadjiev Codes
Tadjiev Codes
9,626 Points
function addToCart() {

        var itemID = document.getElementById("addItemId").value;
        var itemIDColor = document.getElementById("addItemId");
        let itemQty = document.getElementById("addItemQty");
        var addQtyValidationMessage = document.getElementById("addQtyValidationMessage");
        var outputErrorQty = document.createElement('p');



        // iterating and validating if item actually exists in our storeItems array, Loved this .filter ES6 method so helpful to iterate and compare in one line
        let obj = storeItems.filter(x => { return x.productId === itemID });
        console.log(itemID);
        console.log(obj);


        let quantityCart = parseInt(document.getElementById("addItemQty").value);

        let points = 0;

        //VALIDATIONS inside the addtoCart function immediately without a seperate validation function

        if (Number.isInteger(quantityCart)) {
            points++;
        } else {
            itemQty.style.borderColor = "#FF0000";
            alert("Please insert the correct number into blank space!");
            outputErrorQty.innerText += 'Please insert the correct number into blank space!';
            addQtyValidationMessage.appendChild(outputErrorQty);
            outputErrorQty.className = "outputProductErNumber"
        }

        if (quantityCart <= 0) {
            alert('Enter an integer number please!');
            itemQty.style.borderColor = "#FF0000";
            outputErrorQty.innerText += 'Enter an integer number please!';
            addQtyValidationMessage.appendChild(outputErrorQty);
            outputErrorQty.className = "outputProductErNumber";
        } else {
            points++;
        }


        if (quantityCart > obj[0].maxPerCustomer) {
            alert(`Unfortunately, We can't let you buy so many timepieces as they're Limited editions`);
            itemQty.style.borderColor = "#FF0000";
            outputErrorQty.innerText += `Unfortunately, We can't let you buy so many timepieces as they're Limited editions`;
            addQtyValidationMessage.appendChild(outputErrorQty);
            outputErrorQty.className = "outputProductErNumber";
        } else {
            points++;
        }
        // When I run the line 1054 add more items than quantity, it triggers first the 1049 line alert and then the alert of 1055 line
        if (quantityCart > obj[0].quantity) {
            alert(`Unfortunately, We don't have these many watches available in stock `);
            itemQty.style.borderColor = "#FF0000";
            outputErrorQty.innerText += `Unfortunately, We don't have these many watches available in stock `;
            addQtyValidationMessage.appendChild(outputErrorQty);
            outputErrorQty.className = "outputProductErNumber";
        } else {
            points++;
        }

        /*
        if (points === 4) {
            alert("Successful purchase of the Timepiece");
            cartItems.push(new cartItem(itemID, obj[0].price, quantityCart, obj[0].costOfShipping));
            itemIDColor.style.borderColor = "#008000";
            itemQty.style.borderColor = "#008000";
        }
*/

        if (points === 4 && cartItems.find(p => p.productId === itemID)) {
            cartItems[0].quantity++;
            console.log(cartItems.quantity);
            alert("Successful incremented purchase of the Timepiece");
        } else {
            cartItems.push(new cartItem(itemID, obj[0].price, quantityCart, obj[0].costOfShipping));
        }


        console.log(cartItems);
        //Calling the function to display the added Items in the cart
        displayCartItems();
        // calling calculate function here
        calculateCartTotals();

    } // end of the main function   ``` I seem to have understood it now with ur explanation even if late) Now it increments every item in the cart) THe only problem now. The other earlier conditions don't seem to work. Let's say maxpercustomer is 3 but now it adds the 4 items if this item is in the cart. If item is not in the cart the conditions work
Steven Parker
Steven Parker
231,271 Points

It looks like the quantity test is only made against the amount on the form, it doesn't account for the amount already in the cart.

Tadjiev Codes
Tadjiev Codes
9,626 Points

Okay so how to fix that?

if (points === 4) {
            alert("Successful purchase of the Timepiece");
            cartItems.push(new cartItem(itemID, obj[0].price, quantityCart, obj[0].costOfShipping));
            itemIDColor.style.borderColor = "#008000";
            itemQty.style.borderColor = "#008000";
        }``` When  I use my old code like this even if index is 0 in other test conditionals , and i'm adding second, thrid item to the cart, the conditionals work and don'tt add the wrong amount of items to the cart. But when I use the latest .find method then it just adds -1 0 88 like all the invalid numbers. Though when I use my first code in spite of 0 index all the conditional work. What's the reason that it works still with zeros? And what would be the best way to fix the code with the find solution?
Steven Parker
Steven Parker
231,271 Points

You'd probably need to search the cart before doing the "points", so when you get to the part that checks the maximum allowed (which comes before the snippet shown here), you could add what's being requested to what's already in the cart and see if the total exceeds the limit.