Real Estate Website Project

I need some help with my shopping cart functionality in my project. I am new to how rendering API data works for a website. Anyway, the issue I am having is the HTML to communicate with my Javascript to display shopping carts to each real estate card. Most of the shopping cart code I have seen online goes something like:

        <h2 class="section-header">Property Listings</h2>
            <div class="property-items">
                <div class="property-item">
                    <span class="property-item-title">${fomattedaddress}</span>
                    <div class="shop-item-details">
                        <span class="property-item-price">${price}</span>
                        <button class="btn btn-primary shop-item-button" type="button">ADD TO CART</button>
                    </div>
                </div>
<section class="container content-section">
            <h2 class="section-header">CART</h2>
            <div class="cart-row">
                <span class="cart-item cart-header cart-column">ITEM</span>
                <span class="cart-price cart-header cart-column">PRICE</span>
            </div>
            <div class="cart-items">
            </div>
            <div class="cart-total">
                <strong class="cart-total-title">Total</strong>
                <span class="cart-total-price">$0</span>
            </div>
            <button class="btn btn-primary btn-purchase" type="button">PURCHASE</button>
        </section>

Is this something I could do?

I edited this for readability. The triple backticks need to be on their own lines.

<span class="property-item-title">${fomattedaddress}</span>

What are things like this doing? Things like ${fomattedaddress} look like their trying to inject a JS variable but that doesn’t work in HTML. Are you using some library? Is this JSX?

If you want your HTML to “talk” to your JS, you to decide to use click handlers or some kind of event listener.

I’m not sure I understand exactly what you are asking. It’s tough answering a question seeing a code snippet out of context like this unless you ask something specifically about the code. Do you have a particular question about what you posted?

1 Like

Ok, I played around a little bit and got the add to cart button to work. Fetch Request below

fetch("URL", {
	"method": "GET",
	"headers": {
		"API key",
		"Host Info"
	}
})
.then((response) => response.json())
.then((data) => renderProperties(data));

//Render Property Data to Cards
const renderProperties = (properties) => {
  const propertyContainer = document.querySelector(`#propertyContainer`);
	properties.forEach(property => {
	  const propertyCard = document.createElement('div');
		propertyCard.setAttribute('class', 'propertyCard');
	  propertyCard.innerHTML = `
	    <h1>Full Address: ${property.formattedAddress}</h1>

	    <p>Number Bathrooms: ${property.bathrooms}</p>
		  <p>Number Bedrooms: ${property.bedrooms}</p>
		  <p>Property Type: ${property.propertyType}</p>
		  <p>Price: ${property.price}</p>
			<button class="btn btn-primary property-item-button" type="button">ADD TO CART</button>
   `;
   propertyContainer.append(propertyCard);

  });
};


So as you can see I have different cards for property listings. What I need now is in HTML create a shopping bag which is titled “property-items” and then in each bag is of course individual items that is where “property-item” comes in. The question is then how can I call each property listing so I can create functions to add or remove from a shopping cart ( general manipulation)? I thought I could just put in the “property-item” section, ${price} or ${property.price} for example , but that does not seem to work.

OK, so not React, this is just vanilla, just building your HTML in JS and passing it to the DOM.

OK, it’s been a while since I did this (I do React and React Native most of the time). But if you have an array of data to render, and you render it, if you want to remove the second element, you should be able to do some DOM manipulation. I mean, you select all the DOM elements, find the one you want to delete, and remove it from the DOM.

OK, I guess it’s not clear what you are trying to do.

ok I think I might have fixed my initial problem but need help with the solution code. I keep getting error " Cannot read property ‘getElementsByClassName’ of null." Ignore previous code that was my mistake . Code below:

let propertyContainer = document.getElementsById(`#propertyContainer`);
let allItems  = propertyContainer.getElementsByClassName(`fullAddress propType avgPrice`);
let data1 = [].map.call(allItems, fullAddress => fullAddress.textContent);
let data2 = [].map.call(allItems, propType => propType.textContent);
let data3 = [].map.call(allItems, avgPrice => fullAddress.textContent);
  console.log(data1,data2,data3);

//Shopping Cart Functionality
if (document.readyState == 'loading') {
  document.addEventListner('DOMContentLoaded', ready)
} else {
   ready()
}
function ready() {
let removeItemButtons = document.getElementsByClassName('btn-danger')
console.log(removeItemButtons)
for (let i = 0; i < removeItemButtons.length; i++) {
  let button = removeItemButtons[i]
  button.addEventListener('click', removeCartItem)
  }
  let quantityInputs = document.getElementByClassName('cart-quantity-input')
  for (let i = 0; i < quantityInputs.length; i++) {
    let input = quantityInputs[i]
    input.addEventListner('change', quantityChanged)
  }
  let addToCartButtons = document.getElementsByClassName('propertyItems1-button')
  for (let i = 0; i < addToCartsButtons.length; i++) {
    let input = addToCartsButtons[i]
    button.addEventListner('click', addToCartClicked)
  }

document.getElementByClassName('btn-purchase')[0].addEventListener('click', purchaseClicked)
}

function purchasedClicked() {
  alert('Thank You for purchasing a home')
  let cartItems = document.getElementsByClassName('cart-items')[0]
  while(cartItems.hasChildNodes()) {
    cartItems.removeChild(cartItems.firstChild)
  }
  updateCartTotal()
}

function removeCartItem(e) {
  let buttonClicked = event.target
  buttonClicked.parentElement.parentElement.remove
  updateCartTotal()
}
function quantityChanged(e) {
  let input = e.target
  if(isNaN(input.value) || input.value <= 0) {
  input.value = 1
  }
  updateCartTotal()
}

function addToCartClicked(e) {
  let button = e.target
  let propertyItems1 = button.parentElement.parentElement
  let fullAddress = propertyItems1.getElementsByClass('propertyItems1-fullAddress')[0].innerText
	let propType = propertyItems1.getElementsByClass('propertyItems1-propType')[0].innerText
  let price = propertyItems1.getElementsByClass('propertyItems1-price')[0].innerText
  addItemToCart(fullAddress,propType,price)
  updateCartTotal()

}

Didn’t you mean to use getElementsByClassName?

ok so sorry about this but here is the final code. Seems the add to cart buttons are not working like they should. total is not updating and the property listings are not being added to cart.

if (document.readyState == 'loading') {
  document.addEventListner('DOMContentLoaded', ready)
} else {
   ready()
}
function ready() {
let removeItemButtons = document.getElementsByClassName('btn-danger')
console.log(removeItemButtons)
for (let i = 0; i < removeItemButtons.length; i++) {
  let button = removeItemButtons[i]
  button.addEventListener('click', removeCartItem)
  }
  let quantityInputs = document.getElementsByClassName('cart-quantity-input')
  for (let i = 0; i < quantityInputs.length; i++) {
    let input = quantityInputs[i]
    input.addEventListner('change', quantityChanged)
  }
  let addToCartButtons = document.getElementsByClassName('propertyItems1-button')
  for (let i = 0; i < addToCartButtons.length; i++) {
    let button = addToCartButtons[i]
    button.addEventListner('click', addToCartClicked)
  }

document.getElementsByClassName('btn-purchase')[0].addEventListener('click', purchaseClicked)
}

function purchaseClicked() {
  alert('Thank You for purchasing a home')
  let cartItems = document.getElementsByClassName('cart-items')[0]
  while(cartItems.hasChildNodes()) {
    cartItems.removeChild(cartItems.firstChild)
  }
  updateCartTotal()
}

function removeCartItem(event) {
  let buttonClicked = event.target
  buttonClicked.parentElement.parentElement.remove
  updateCartTotal()
}
function quantityChanged(event) {
  let input = event.target
  if(isNaN(input.value) || input.value <= 0) {
  input.value = 1
  }
  updateCartTotal()
}

function addToCartClicked(event) {
  let button = event.target
  let propertyItems1 = button.parentElement.parentElement
  let fullAddress = propertyItems1.getElementsByClassName('propertyItems1-fullAddress')[0].innerText
	let propType = propertyItems1.getElementsByClassName('propertyItems1-propType')[0].innerText
  let price = propertyItems1.getElementsByClassName('propertyItems1-price')[0].innerText
  addItemToCart(fullAddress,propType,price)
  updateCartTotal()

}

function addItemToCart(fullAddress, propType, price) {
    let cartRow = document.createElement('div')
    cartRow.classList.add('cart-row')
    let cartItems = document.getElementsByClassName('cart-items')[0]
    let cartItemNames = cartItems.getElementsByClassName('cart-item-fullAddress')
    for (var i = 0; i < cartItemNames.length; i++) {
        if (cartItemNames[i].innerText == fullAddress) {
            alert('This item is already added to the cart')
            return
        }
    }

    let cartRowContents = `
        <div class="cart-item cart-column">
            <span class="cart-item-fullAddress">${fullAddress}</span>
						<span class="cart-item-propType">${propType}</span>
        </div>
        <span class="cart-price cart-column">${price}</span>
        <div class="cart-quantity cart-column">
            <input class="cart-quantity-input" type="number" value="1">
            <button class="btn btn-danger" type="button">REMOVE</button>
        </div>`
    cartRow.innerHTML = cartRowContents
    cartItems.append(cartRow)
    cartRow.getElementsByClassName('btn-danger')[0].addEventListener('click', removeCartItem)
    cartRow.getElementsByClassName('cart-quantity-input')[0].addEventListener('change', quantityChanged)
}

function updateCartTotal() {
    let cartItemContainer = document.getElementsByClassName('cart-items')[0]
    let cartRows = cartItemContainer.getElementsByClassName('cart-row')
    var total = 0
    for (let i = 0; i < cartRows.length; i++) {
        let cartRow = cartRows[i]
        let priceElement = cartRow.getElementsByClassName('cart-price')[0]
        let quantityElement = cartRow.getElementsByClassName('cart-quantity-input')[0]
        let price = parseFloat(priceElement.innerText.replace('$', ''))
        let quantity = quantityElement.value
        total = total + (price * quantity)
    }
    total = Math.round(total * 100) / 100
    document.getElementsByClassName('cart-total-price')[0].innerText = '$' + total
}

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.