[Fixed]-Change model data in page on click

1πŸ‘

βœ…

I suggest you use AJAX instead classic rendering for this. For example:

Add an data-key attribute to store the product code.

{% for product in products %}
  {% if product.productType == productType %}
    <li>
      <a data-key={{product.code}} href="#" onClick="onProductClicked(this)">
          {{ product.productName }}
      </a>
    </li>
    {% endif %}
{% endfor %}

Then, when you click a product, get it’s code and make an ajax request to the API to retrieve it’s products data.

onClickedProduct(product) {
  const productKey = $(product).getAttribute('data-key');
  $.get(`/api/products/${productKey}`, function(product) {
    loadProductDescription(product.description);
    loadProductGallery(product.gallery);
    loadProductManual(product.manual);
  });
}

function loadProductDescription(description) {
  $('#product-name').text(description.name);
  $('#product-detail').text(description.detail);
}

function loadProductManual(manual) {
  $(manual).each(function(index) {
    $('#tab2 li').eq(index).text($(this));
  });
}

function loadProductGallery(gallery) {
  $(gallery).each(function(index) {
    $('#tab3 img').eq(index).src = 
        `data:image/png;base64,${$(this)}`;
  });
}

Where /api/products/:productKey is the path to the backend API to fetch the product with that code.

Leave a comment