Modifying various items depending on the variable's value

I'm attempting to adjust various variables depending on which button the user clicks. For instance, there are three buttons:

<button id="button1" onclick="isClicked(this.id)">B1</button>
<button id="button2" onclick="isClicked(this.id)">B2</button>
<button id="button3" onclick="isClicked(this.id)">B3</button>

There are also 3 objects:

var button1 = { someValue: 0, otherValue: 5 };
var button2 = { someValue: 0, otherValue: 5 };
var button3 = { someValue: 0, otherValue: 5 };

The ID of the clicked button is passed into the JavaScript function as shown below:

function isClicked(clicked_id) {
    selectedID = (clicked_id);
}

My goal is to change the value of a variable based on the clicked button - so if button1 is clicked, modify the button1 object, and if button2 is clicked, update the button2 object.

I have explored resources like Programmatically setting the name of a variable and Programmatically set variable names by appending an ID parameter but I haven't found a solution that fits my situation.

Is there a more effective approach to accomplish this task?

Answer №1

Organize your elements within:

var cards = {
    card1 : { valueA: 10, valueB: 20 },
    card2 : { valueA: 15, valueB: 25 },
    card3 : { valueA: 12, valueB: 22 }
};

Next step:

function isSelected(selected_id) {
    var selectedCardObject = cards[selected_id];
    // perform action
}

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

NestJS: Specify the data type for @Body()

Consider the code snippet below: @Post() public async createPet(@Body() petDetails: PostPetDto): Promise<any> { } In this scenario, the type of @Bod() petDetails defaults to plain/any instead of the declared type of PostPetDto. What is the recommen ...

Optimal method for storing large arrays of numbers in localStorage using JavaScript

*"Efficient" in this context refers to smaller size (to reduce IO waiting time) and fast retrieval/deserialization times. Storing times are less important in this scenario. I need to store multiple arrays of integers in the browser's localStorage, ea ...

ng-class does not seem to be functioning properly when used within a file that is included via ng-include in

My question pertains to the menu I am loading using ng-include from the index file. <span ng-include="'app/components/common/menu.html'"></span> The content of menu.html is as follows: <li ng-class="active" > <a hr ...

How can Node / Javascript import various modules depending on the intended platform?

Is there a way to specify which modules my app should import based on the target platform in TypeScript? I am interested in importing different implementations of the same interface for a browser and for Node.js. In C++, we have something like: #ifdef wi ...

Exploring object manipulation and generating unique identifiers by combining values - a beginner's guide

After analyzing the provided data, my goal is to come up with a method of combining the IDs and returning an array of their corresponding keys. // example data var data = [ { id: 1, key: 'a' }, { id: 1, key: 'b' }, { id: 2, key ...

Guide on transferring value from a <select> element using JavaScript

I'm attempting to pass the selected value of a <select> in the onChange function. I've explored this question on SO, but unfortunately, using this and this.value hasn't been successful. I understand that the question is quite old... se ...

Tips for signaling to an AngularJS form that the input value has been altered

I developed a sign up form using angularjs. The submission process is functioning correctly. Now, I want to implement validation to check if the email provided is already registered. If it exists, display an error message indicating that the email is alrea ...

Navigating Angular's Resolve Scope Challenges

As a junior developer, I've been diving into Angular.js and exploring the resolve feature of the route provider to preload my Project data from a service before the page loads. Previously, I was fetching the data directly inside the controller. Howeve ...

Error message in Angular about undefined JavaScript function

Struggling to make my Angular 17 project functional with Bootstrap (5) and the datePicker feature. Despite following tutorials, I keep encountering a "ReferenceError: datePicker is not defined" error during the app build process. Here are the steps I&apos ...

Tips for automating the activation of intents at specific scheduled times in Dialogflow

I'm attempting to automatically trigger intents in Dialogflow to obtain the user's contact details at a scheduled time. Is it possible to achieve this using JavaScript? If so, could you please provide the code? ...

Is there a way to utilize OpenLayers to showcase various icons for distinct features all within one layer?

Being new to Openlayers/JS and fairly inexperienced with programming in general, there may be other issues in my code that I'm unaware of. I am currently using the latest version of Openlayers (5.3.0). My application sends GeoJson formatted data via ...

I am looking to showcase the information from two separate collections

I am looking to display data from two separate mongoose collections. I have a Member collection and a Property collection. Below is my code for fetching the data: const Property = require('../models/propsSchema') const Members = require(&apo ...

What is the best way to eliminate a duplicate item from the shopping cart without actually deleting it?

I developed an e-commerce platform with a cart feature using the context API. However, I encountered an issue where removing one item from the cart also deletes another item if there are two of the same items in the cart. How can this be prevented? Below ...

Retrieving Records within a Specific Date Range for Check-ins and Check-outs

Our team is currently working on developing booking software that requires handling different room pricing based on specific dates. Each room has distinct pricing for weekdays and weekends. ROOM 1 Pricing 1: September 1st - November 3rd, Weekday: $100, W ...

What is the process of using the split() method to extract specific text from a string in JavaScript?

Working with AngularJS and facing a requirement to extract a specific text from a scope value. Here's my scope value: $scope.myLogMsg = '1111 order is placed by Sukumar Ms(User)'; //output: by Sukumar Ms(User) Desired output: by Sukumar Ms ...

Why is Reactjs axios returning a promise instead of the expected value?

I have been attempting to retrieve data from an API using axios, but all I am getting back is a Promise. The Node.js code: router.get('/isAdmin/:userId/:groupeId', async (req, res) => { let userId = req.params.userId let groupeId = ...

How to create a dropdown menu in React js with an array of items

Can we structure the array without splitting it into two parts and iterating over them? arrayList=[Jeans, Jackets, Pants, Fragrance, Sunglasses, Health Products] <div className='Flexbox'> //arrayList1.map](//arrayList1.map)(x=>return(< ...

Encountering a "Start script missing" error while trying to execute npm start, the problem remains even after attempting

Help, I keep encountering this issue npm ERR! missing script: start whenever I attempt to execute 'npm start' for my latest React project. I've tried searching for a solution and came across some individuals who were able to resolve it by u ...

The art of revealing and concealing code blocks in AngularJS

I am currently working on a task in my AngularJS project. The requirement is that when both point directives within the md-autocomplete code are filled, the results directive should be displayed immediately without the need for any button. Additionally, if ...

Missing callback pattern in NodeJS

When I spend hours writing NodeJS code, there's a common scenario that leaves me unsure of how to proceed. Take the following async function call (where we forget the necessary callback): function foo (callback) { // Perform a task and call callba ...