Choose the current div using JavaScript

Looking to add the selected product along with its quantity and price to another div tag using the jQuery click function. Each time I click, only the first array value of the variable "product" is displayed.

How can I access the values of the current row for the table?

Utilizing Twig template:

<tr>
<td class="reference">{{product.reference}}</td>
<td class="product">{{product.productNr}} </td>
<td class="product">{{product.productDesp}} </td>
<td class="price">{{product.price}}</td>
<td class="input"><input type="text" /></td>
<td class="warenkorb"><button type='submit'>in den Warenkorb</button></td>
</tr>

<div id="cart">
<!-- Selected product by the user will appear here -->
???????
</div>

My JavaScript code:

$('.warenkorb').click(function(){
           var reference = $('.reference').text();
            alert(reference);
        });

});

Data:

 ------------------------------------------------------
| reference | product | ProductNr | quantity | price |
______________________________________________________
|Jack store| Apple    | 12435436  | 7        | 70€   |
______________________________________________________
|Bill store| Apple    | 32534534  | 4        | 34€   |
______________________________________________________

Answer №1

To reference the element that was clicked, you can utilize the this element. By using jQuery, you can easily select the desired values from the appropriate row.

$('button[type=submit]').click(function(){
    var $parent = $(this).closest('tr'),
        name = $parent.find('.product-name').text(),
        quantity = $parent.find('.input input').val() || 1,
        price = $parent.find('.price').text();

   $('#cart').text(quantity + 'x ' + name  + ' - ' + price);
});

JSFiddle

Answer №2

Give this a shot:

$('.cart-button').click(function() {
  var closestTr = $(this).closest('tr');
    
    var reference = closestTr.find('.ref').html();
    var product = closestTr.find('.item').html();
    var price = closestTr.find('.cost').html();
    var textdata = closestTr.find('input').val();
    
    // Add item to the top of the cart
    $("#cart").prepend(reference+"|"+product+"|"+price+"|"+textdata);
  
     
    // Add item to the bottom of the cart
    $("#cart").append(reference+"|"+product+"|"+price+"|"+textdata);
  
    // Replace cart data with the latest item
    $("#cart").html(reference+"|"+product+"|"+price+"|"+textdata);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table>

<tr>
  <td class="ref">a1</td>
  <td class="item">a2</td>
  <td class="cost">a3</td>
  <td class="input">
    <input type="text" />
  </td>
  <td class="cart-button">
    <button type='submit'>Add to Cart</button>
  </td>
</tr>

<tr>
  <td class="ref">b1</td>
  <td class="item">b2</td>
  <td class="cost">b3</td>
  <td class="input">
    <input type="text" />
  </td>
  <td class="cart-button">
    <button type='submit'>Add to Cart</button>
  </td>
</tr>

</table>
<div id="cart">
  <!-- Selected items will appear here -->
  ????????
</div>

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

Angular 14 is experiencing issues with NgRx Store failing to properly recognize the payload

The issue lies in TypeScript not recognizing action.payload.index as a valid property. I am unsure how to resolve this problem and make the 'index' visible in my project. shopping-list.actions.ts import {Action} from "@ngrx/store"; im ...

Creating auto serial numbers in the MERN stackWould you like to know how to

I need help coming up with a way to automatically generate serial numbers for my "ticketno" field. Every time a user creates a new application ticket, the ticket number should increment by one. Can someone guide me on how to achieve this? This i ...

The sticky header is malfunctioning due to a null offsetTop value

import React , {useRef, useEffect} from 'react' import './header.css' const nav_links =[ { path:'#home', display:'Home' }, { path:'#about', display:'About& ...

Generating text upon clicking by utilizing vue apex charts dataPointIndex

Is there a way to populate a text area on click from an Apex chart? The code pen provided below demonstrates clicking on the bar and generating an alert with the value from the chart. Instead of displaying this value in an alert, I am looking to place it o ...

When I try to alter HTML using JS, I encounter an undefined error related to AngularJS

Using this specific function: function adjustContent(elemento){ if (document.getElementById(elemento).innerHTML.indexOf('&#10004;')>0){ document.getElementById(elemento).innerHTML=document.getElementById(eleme ...

Hold off on advancing until the particular text is found in the DOM element

One of the challenges I'm facing is creating a function that waits for specific text to change before returning a value: function getElementText() { while(isLoading()) { } return $('#element').text(); } function isLoading() { ...

What is the best way to transmit two distinct sets of data from a child component to the v-model of a parent component?

Currently, I am working on a project using vuejs 2 and typescript. In this project, I need to pass two different sets of data - data and attachments - within the parent component. I am utilizing vue-property-decorator for this purpose. However, I am facing ...

Using dynamic, deferred loading of scripts in JavaScript

Is it necessary to create a reference for a dynamic, lazy import that is used multiple times in a script? For example, if there are 2 event handlers importing different functions from the same module: /* index.js */ window.addEventListener("click", (e) =&g ...

What is the best way to remove all elements in jQuery?

I need to remove the selected element in my demo using jstree. I have consulted the plugin's API at http://www.jstree.com/api/#/?f=deselect_all([supress_event]), but it seems that it does not deselect the item properly. Here are the steps I have follo ...

Ways to Retrieve the Text From the Selected Index in Datalist Element

I need to extract the inner text of the option tag using pure JavaScript This is the HTML code I am working with: <input list="in" name="i_n" class="form-control" placeholder="Enter Item Name" required> <datalist id="in" onChange="rate(this)"&g ...

Create a Rest API and implement server-side rendering concurrently using SailsJs

I am exploring the potential of utilizing the SailsJs framework for nodeJs in order to create an application. Initially, my plan was to construct a REST API in Sails and utilize AngularJs for managing the Front-End. This API would also be beneficial for o ...

A comprehensive guide on personalizing Bootstrap 4 tooltips to suit your specific needs

I would like to customize the tooltip in Bootstrap 4 based on the screenshot provided below: https://i.stack.imgur.com/wg4Wu.jpg <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta chars ...

Nested rendering in React involves the process of rendering a

I have a collection with various arrays structured like this: const Items = { Deserts: [{name:cookies}, {name:chocolate}], Fruits: [{name:apple}, {name:orange}] ... } My goal is to display it as: <title>Deserts</title> Cookies Chocolate &l ...

Endless loop of jquery textbox focus event

Currently, I am employing jQuery for validating textbox values. I have two textboxes - txt1 and txt2. For this purpose, I have created a jQuery function: $("#txt1").blur(function () { if ($("#txt1").val() == "") { $("#scarrie ...

Obtaining a button from a dialog in Google Apps

It seems like I'm overlooking something really simple here, but I'm struggling to enable an interface button from a dialog box in Google Apps. When I try setting the disabled attribute to false in a this object under the "click" function, the bu ...

Pause and wait for the completion of the Ajax call within the function before assigning the object to an external variable

In my quest to leverage JavaScript asynchronously to its full potential, I am looking for a way to efficiently handle received data from API calls. My goal is to dynamically assign the data to multiple variables such as DataModel01, DataModel02, DataModel0 ...

What is the best way to retrieve the current URL with a hashtag symbol using JavaScript?

I am attempting to display the current URL after the question mark with a hash symbol using PHP, but unfortunately, it is not achievable. Therefore, I need to utilize JavaScript for this task, even though I have limited knowledge of it. This is the specifi ...

Employing JavaScript for fading divs in and out sequentially

Hey there! I'm currently struggling with implementing transitions for my tool tips. Any assistance would be greatly appreciated! I am looking to have my "fader" divs fade in and out on click of a button, with each transition lasting 5 seconds. It&apo ...

Using NextJs to track the position of a scrollbar

Incorporating NextJs for Server Side Rendering has been a game-changer for me. I've also implemented a navbar in my application that needs to adjust styles based on the scroll position. Is there a way to determine if the window has scrolled beyond 100 ...

Invalid file name detected during the download process

Below is the Javascript code I currently use to download a pdf: var link = document.createElement('a'); link.innerHTML = 'Download PDF file'; link.download = "Report.pdf"; link.href = 'data:application/octet-stream;base64 ...