Make sure to transfer any data retrieved from a click event using JavaScript into a different field

Recently I delved into learning JavaScript and stumbled upon a coding problem that has me stumped!

I'm looking for a way to display information in the blue area after selecting an option, showing details like the name of the food item and its price.

If anyone can provide guidance on how to proceed with this task, I would greatly appreciate it. Thank you in advance for your help!

let plan = document.querySelector('.paln');
let price = document.querySelector('.price');

let item = document.querySelectorAll('.item');

for (var i = 0; i < item.length; i++) {
  item[i].addEventListener('click', showplan, false);
}

function showplan() {
  console.log('hello')
}
.product_list {
  display: flex;
}

.product_list .item {
  border: 1px solid #ccc;
  border-radius: 6px;
  text-align: center;
  padding: 20px;
  margin: 20px;
}

.product_list .item h2 {
  margin-bottom: 16px;
}

.product_list .item:hover {
  border: 1px solid #222;
}

.product_list .bold {
  border: 3px solid;
}

.show {
  border: 2px solid blue;
  padding: 20px;
}
<ul class="product_list">
  <li class="item">
    <h2>coke</h2>
    <p>$100</p>
  </li>
  <li class="item">
    <h2>fries</h2>
    <p>$600</p>
  </li>
</ul>

<h2 class="show">Your food of choice is<span class="plan"></span>price is<span class="price"></span></h2>

Answer №1

To retrieve the target object when clicked, you can click anywhere within a <li> element and have your target be either the h2 or <p>. In order to achieve this, you must locate the closest <li> tag.

let plan = document.querySelector('.plan');
let price = document.querySelector('.price');

let item = document.querySelectorAll('.item');

for (var i = 0; i < item.length; i++) {
  item[i].addEventListener('click', showplan, false);
}

function showplan(e) {
  const planSelected = e.target.closest('li').querySelector('h2');
  const priceSelected = e.target.closest('li').querySelector('p');
  plan.innerHTML = planSelected.innerHTML;
  price.innerHTML = priceSelected.innerHTML;
}

Answer №2

By clicking on any of the buttons, a function is triggered that modifies the content inside .show

document.getElementById("item1").addEventListener('click', () => {document.querySelector(".show").innerText = "Your choice: Coke Price: $100";})
document.getElementById("item2").addEventListener('click', () => {document.querySelector(".show").innerText = "Your choice: Fries Price: $600";})
.product_list {
  display: flex;
}

.product_list .item {
  border: 1px solid #ccc;
  border-radius: 6px;
  text-align: center;
  padding: 20px;
  margin: 20px;
}

.product_list .item h2 {
  margin-bottom: 16px;
}

.product_list .item:hover {
  border: 1px solid #222;
}

.product_list .bold {
  border: 3px solid;
}

.show {
  border: 2px solid blue;
  padding: 20px;
}
<ul class="product_list">
  <li class="item" id="item1">
    <h2>coke</h2>
    <p>$100</p>
  </li>
  <li class="item" id="item2">
    <h2>fries</h2>
    <p>$600</p>
  </li>
</ul>

<h2 class="show">Your choice:<span class="plan"></span> price:<span class="price"></span></h2>

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

Styling on a device can vary from how it appears on a

Using Ionic2, I have an application with messages. In a browser, the message appears like this: https://i.stack.imgur.com/SyCtM.png However, when running on either an Android or iOS device, it looks different: https://i.stack.imgur.com/i0RdO.png The di ...

Learning how to interpret input from the command line in Vertx

Would appreciate some guidance on how to read command line arguments in vert.x using JavaScript. For instance, I am wondering how to go about reading: arguments(arg1, arg2, arg3) vertx run example.js arg1 arg2 arg3 ...

The issue with Extjs store.proxy.extraParams being undefined appears to only occur in Internet Explorer

I currently have an ExtJs store set up with specific configurations. var fieldsStore = new Ext.create('Ext.data.Store', { model : 'FieldsModel', proxy : { type : 'ajax', url : 'queryBuilder_getQueryDetails', ...

Developed a verification process using Discord.JS, however, I'm not receiving any feedback when trying to configure the command

As I embark on creating my debut Discord bot to enhance my coding skills, I have encountered numerous hurdles along the way. While most of these challenges were overcome by me independently, this particular issue has left me stumped. The objective of the ...

Add an item in the middle of the content contained in a div element

I am looking to add a line break ( ) element right before the "finish" text within the div element. <div>start finish</div> Using jQuery, I aim to achieve this modification dynamically. ...

Sending MVC3 model information as JSON to a JavaScript block

My challenge is to correctly pass my MVC3 model into a script block on the client side. This is the approach I'm taking in my Razor view: <script type="text/javascript"> var items = @( Json.Encode(Model) ); </script> The "Model" in t ...

The Spring MVC controller is not designed to handle direct AJAX requests

In my server-side controller, I have the following method: @RequestMapping(value = {"/templates/test"}, method = RequestMethod.POST, consumes = "application/json") @ResponseBody public String TestURL(@RequestBody List<String> testString, ...

The functionality of AngularJs' scope.apply appears to interfere with the autocomplete feature of jQuery UI

I'm having difficulty implementing an autocomplete field into a directive using Jquery-UI. Let me explain. Here is my html element : <div class="form-group" > <input type="text" placeholder="Find a category" data-category-autocomplete dat ...

Error: Trying to assign a value to a null property

I am facing an issue while trying to dynamically create "iframe's textarea" and insert the value of a variable. Unfortunately, I keep encountering an error. Any suggestions on how to resolve this problem? P.S: Using Google Chrome as the browser ...

How to Align <ul> to the Right in Bootstrap 4

Looking to align a list to the right in the header section, here is the code snippet: <div class="collapse navbar-collapse" id="app-header-nav"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item"> <a class=" ...

Acquire a specified number of items from every category using TypeScript

I need to extract N items from each group within a list using Typescript. In C# with LINQ, I would achieve something similar like this but I am unsure of the equivalent in TypeScript. var rr = db.Products.GroupBy(x => x.ProductSubTypeCategoryId).Select ...

PHP code isn't properly redirecting to AJAX calls

I have the following JavaScript code that validates a form by calling a PHP script on the backend: $(function() { // Setting up form validation for the #register-form element $("#register_form").validate({ // Specifying the validation ru ...

Bigger than 100x100 Soundcloud profile picture size

Is it possible to retrieve a user's image larger than 100x100 using the Soundcloud API? Upon reviewing their documentation, I have not come across any images exceeding this size: An ideal solution would involve some form of Javascript implementation. ...

Following the 'GoRails' tutorial, I have successfully integrated notifications into my Rails application

Recently, I've been working on implementing a notification system following a tutorial. Everything was going smoothly until I started writing Coffeescript. The specific script causing the issue is as follows: class Notifications constructor: -> ...

Exploring the inner structure of an STL Object with the power of three.js

Currently, I am attempting to create a cross section of a heart model that I have imported using the STLLoader function in three.js. To achieve this, I am experimenting with the ThreeCSG wrapper for the csg.js library, similar to the approach outlined in t ...

How can we combine Angular Gradients and CSS Webkit Gradients for a modern design

Can a gradient be created that resembles the color picker style shown here? The outer part showing full saturated, 50% brightness values and transitioning towards the inside to 100% brightness. https://i.sstatic.net/ohuF4.jpg ...

Create HTML content from a file retrieved from the server

I have been working on a dynamic website project, diving into web development from scratch despite having coding experience in general. As I navigate Angular CLI and Bootstrap, I've come across a fundamental question: Do modern websites house all thei ...

What is the best way to prevent a selected <option> in one <select> from being selected in another <select>, while also making sure this applies to both new and existing &

Currently, I am working with a code snippet that disables select options based on similar fields. The code can be found here. $(document).on('shown.oc.popup', function() { let options = $('.variantPlacementOptions:first select').c ...

Retrieving Files from POST Request Body Using Node.js and Angular

Currently, I am developing a MEAN Stack application and facing an issue while handling a form that should allow users to upload a file upon submission. The process seems to work seamlessly on the client side; however, when I inspect the request body after ...

Struggling with setting up and installing the MDX transformer plugin (as well as its dependencies) on a Gatsby site

Task: Currently working on setting up a basic blog using Gatsby Results: Expected Result: Following the tutorial guide as expected Actual Result: Encountering Dependency tree error at certain steps & also receiving a warning message stating 34 vulnerab ...