An easy way to retrieve the accurate price based on quantity from a list using Cakephp 2.x

I am currently working on a listing page that displays item name, price, and quantity. My goal is to implement a feature where if a user increases the quantity of an item from the list, the price will also change accordingly. Below is a snippet from my file view_item.ctp:

<?php
  foreach($result as $k=>$v) { ?>

  <tr class="hide_me_<?php echo $v['Inventory']['id']; ?> ">
  <td><i class="fa fa-chevron-right"></i></td>
  <td><?php echo $v['Inventory']['item_name']; ?></td>
  <td class="text-center">
  <span class="box-plush" id='plusbutton' onclick="itemQty(<?php echo 
   $v['Inventory']['id']; ?>,'incr')"><i class="fa fa-plus"></i></span>

  <span class="box-dgt" id='att_<?php echo $v['Inventory']['id']; ?
  >'>1</span> 

 <span class="box-minus" id='minusbutton' onclick="itemQty(<?php echo 
 $v['Inventory']['id']; ?>,'decr')"><i class="fa fa-minus"></i> </span> 
 </td>

 <td class="text-center" id='price_<?php echo $v['Inventory']['id']; ?>'><?
 php echo $v['Inventory']['item_price']; ?></td>

 <td class="text-right"><?php echo  $v['Inventory']['item_price']; ?></td>

 <td class="text-center">
     <a class="btn btn-danger btn-sm close-box" href="javascript:void(0)" 
     onclick="menuItem(<?php echo $v['Inventory']['id']; ?>)">
      <i class="fa fa-times" ></i>
     </a> 
 </td>
 </tr>
 <?php } ?>

 <script type="text/javascript">
   function menuItem(id){
   $('.hide_me_'+id).hide();
 }


  function itemQty(id,action){
    var qty = $('#att_'+id).text();
    qty = parseInt(qty);

  if(action=="incr"){
    $qty1 = qty+1;
  }else{
    $qty1 = qty-1;
  }  

    $('#att_'+id).text($qty1);
  }
  </script>

Answer №1

Substitute the

onclick="itemQty(<?php echo $v['Inventory']['id']; ?>,'decr')"
with
data-row="<?php echo $v['Inventory']['id']; ?>"

Include

id="total_<?php echo  $v['Inventory']['item_price']; ?>

within this line

<td class="text-right"><?php echo  $v['Inventory']['item_price']; ?></td>

so it turns into

<td class="text-right" id="total_<?php echo  $v['Inventory']['item_price']; ?>"><?php echo  $v['Inventory']['item_price']; ?></td>

Alter your itemQty function to compute price

function itemQty(id, action) {
    let qty = $('#att_' + id).html();
    qty = parseInt(qty);

    if (action == "incr") {
      qty++;
    } else {
      qty--;
    }

    $('#att_' + id).html(qty);

    let price = parseFloat($('#price_' + id).html());
    let total = price * qty;
    $('#total_' + id).html(total.toFixed(2))
  }

then append these lines at the end

  $(document).ready(function() {
    $('#plusbutton').on('click', function() {
      itemQty($(this).data('row'), 'incr')
    })

    $('#minusbutton').on('click', function() {
      itemQty($(this).data('row'), 'decr')
    })
  })

preview available at: https://jsfiddle.net/shahonseven/gn8sees8/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I keep encountering the error message "ReferenceError: window is not defined" in Next.js whenever I refresh the page with Agora imported. Can someone explain why this is happening?

Whenever I refresh my Next.js page with Agora SDK imported, I keep encountering the error "ReferenceError: window is not defined". It seems like the issue is related to the Agora import. I attempted to use next/dynamic for non-SSR imports but ended up with ...

What is the procedure for canceling a readline interface inquiry?

TL;DR I encountered an issue with the native Node.js Readline module. Once a question is asked using rl.question(query[, options], callback), it seems there is no straightforward way to cancel the question if it's pending an answer. Is there a clean ...

Utilizing the Command Line/Window feature within Visual Studio Code

As a newcomer to Visual Studio Code, I'm currently using the latest Version: 1.29.1. When I used Matlab, I had access to a script window for writing code, a Command Window for testing code snippets and viewing variable values, as well as a workspace ...

Using Javascript/HTML to enable file uploads in Rails

I'm currently facing an issue with uploading and parsing a file in Rails, as well as displaying the file content in a sortable table. I followed a tutorial on to get started. This is what my index.html.erb View file looks like: <%= form_tag impo ...

Utilizing additional JavaScript libraries with custom Power BI visuals

Seeking clarification on how to use the d3 library within my visual.ts file. I have installed it using npm and added it to the externalJS section of pbiviz.json, but I am unsure of any additional configurations needed to successfully include and utilize it ...

Slower CSS rendering as Javascript finishes its tasks

I am currently dealing with a jQuery plugin that is quite large and complex, but I will not be sharing it here to keep things simple. The issue I am facing is relatively straightforward, so I will focus on the essential code snippets: There is a click eve ...

There seems to be an issue with the Axios Post not consistently finishing each time

I'm a newcomer to React and running into some issues. Here is the API call I am currently using. Axios.post(Addr_currentRound_addOne, { gameId: gameId }).then(history.push("/leiter_tunierplan/"+gameId)); And here is the corresponding API c ...

Angular Typescript subscription value is null even though the template still receives the data

As a newcomer to Angular and Typescript, I've encountered a peculiar issue. When trying to populate a mat-table with values retrieved from a backend API, the data appears empty in my component but suddenly shows up when rendering the template. Here&a ...

Rearranging the img element within the dom structure to optimize display in various blog posts

Hey there, I have a specific task that I need help with: Currently, I am using Business Catalyst as my framework. They have a blog module that does not offer much customization when it comes to blog lists. There is a preview tag that displays a preview of ...

Unable to activate IndexedDb persistence with Firebase v9 in a Next.js PWA

I'm having trouble enabling IndexedDb persistence in Firebase v9 for a Next.js PWA. These errors keep popping up: index.js // main Firebase file import { initializeApp } from 'firebase/app' import { getAuth } from 'firebase/auth' ...

The cross-domain AJAX request fails to receive a response

I am currently working on validating PAN card details. I am utilizing an AJAX call to verify the PAN card entered by the user, sending the PAN number to this URL: . The data is being sent to the following URL using AJAX call: function callbackFnc(data) { ...

Is there a way to modify the material of individual objects in THREE.js without creating separate Meshes?

We have developed a unique PCB Viewer using THREE.js, but now we want to enhance it with selection functionality. While the task itself isn't complex and I have managed to make it work, I am encountering performance challenges. Our goal is to allow us ...

What is the best way to access the rendered child components within a parent component?

I am seeking a way to retrieve only the visible child components within a parent component. Below is my unsuccessful pseudo-code attempt: parent.component.html <parent (click)="changeVisibility()"> <child *ngIf="visible1"></child> ...

Using global variables for mocha testing (and babel setup)

Currently, I am developing a library using es6 and transpiling it with babel via webpack and npm. However, I have encountered an issue where my library has a dependency on some code that cannot be modified but is required for my library to function properl ...

There seems to be an issue with the function code error when calling it within the

When I attempt to run my code in this way, I encounter a compile time error stating that the expression statement is not an assignment or call... (within the else statement). What am I missing here to get it to work? I've made numerous attempts to ad ...

Customizing blockquote styling in QuillJS with a unique class

Currently, I am exploring a method to include a custom class when the user selects the blockquote toolbar button. When the blockquote is clicked, it generates the following element: <blockquote class="ql-align-justify">this is my quoted tex ...

How can I make sure my rows are properly aligned using the Grid

Looking at the image below, I am attempting to align "Ticket Number" and "Email" using a Grid: View My Result Image <Grid container direction="row" justifyContent="flex-start" alignItems="stretch" style={{ pad ...

Analyzing and refreshing the data entries in firebase database

https://i.stack.imgur.com/ZMjck.png I have been attempting to modify my Username password group name. However, the update process is not successful. I am looking for a way to compare data before updating fields, but I am unable to find a suitable method. ...

Is there a way to incorporate a CSS file into this without explicitly mentioning the color?

I have successfully implemented a PHP solution for changing themes with a cookie that remembers the selected theme color when the user leaves the site. However, I now need to switch this functionality to JavaScript while still utilizing the CSS file. How c ...

Ensuring the correctness of a JSP form prior to submitting it

I am experiencing an issue with my form in JSP. The input fields are marked as "required", but when I submit the form, it still allows submission even if the required fields are empty. I am confused by this behavior and would greatly appreciate any help. ...