Connect user input to a predefined value within an object

I am currently working on developing a timesheet application that allows users to input the number of hours they work daily. The user data is stored in an object, and I aim to display each user's hours (duration) in an input field within a table. An image demonstrating the desired data structure can be found here: https://i.sstatic.net/tUHUx.jpg

You can also view a fiddle of the project here: https://jsfiddle.net/h64wafkp/14/

In this database, each user has a one-to-many relationship with another table named "hours". Here is an example of the JSON data structure:

 {
"id": 1,
"firstname": "JayZ",
"lastname": "Carter",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfd5dec6ffcdd0dcded9dac7ded0d2">[email protected]</a>",
"hours": [
  {
    "id": 226,
    "user_id": 1,
    "date": "2018-12-05",
    "duration": 140
  },
  {
    "id": 1,
    "user_id": 1,
    "date": "2018-12-02",
    "duration": 13
  },
  {
    "id": 2,
    "user_id": 1,
    "date": "2018-12-03",
    "duration": 13
  }
]

},

The table itself is a standard HTML table with each day as column headers. My challenge lies in linking each duration to the corresponding date cell (refer to the above image). Any advice or suggestions would be appreciated.

Answer №1

Create a function within your methods to retrieve the duration for a specific user and date:

getDuration(user_id, date) {
    const user = this.users.find(user => user.id == user_id);
    const hour = user.hours.find(hour => hour.date == date);
    return hour ? hour.duration : 0;
},

Next, include a :value attribute in the HTML part of the input element:

:value="getDuration(user.id, day)"

If you want to enable updates to these input values that reflect back on the data structure, define a function setDuration and use the following attribute with the input tag:

@input="e => setDuration(user.id, day, e.target.value)"

In order to update the user's hours array as needed, you may have to add a new hour object with a unique id value. If you're unsure how to generate new id values, you'll need to implement that functionality yourself (refer to the comment):

setDuration(user_id, date, duration) {
    const user = this.users.find(user => user.id == user_id);
    const hour = user.hours.find(hour => hour.date == date);
    if (hour) {
        hour.duration = duration;
    } else {
        user.hours.push({
            id: getNewId(), // <--- implement this!
            user_id,
            date,
            duration
        });
    }
},

Following our discussion, it appears that if there is no existing id property, your ORM will understand that an hour record should be inserted rather than updated. In such cases, you can simply remove the line:

            id: getNewId(), // <--- implement this!

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

Ways to modify Angular pipe without specifying data types

I am in the process of extracting an Angular pipe from an application to a library. The current pipe is tied to specific types, but I want to change it to use generic types while maintaining type safety. Original Pipe: import { Pipe, PipeTransform } fr ...

Issue encountered with search.run().getRange function when accessing a stored search in suitescript 2.0

I am facing an issue with my saved search in the beforeLoad userevent script. After adding a filter and running the search, Netsuite throws an UNEXPECTED_ERROR. Any ideas on what might be causing this error? var poRec = context.newRecord; var countIt ...

Tips for maintaining an updated array's consistency on page refresh in Vue.js?

HelloWorld.vue Dynamic routing in Vuejs: <template> <div> <b>Vuejs dynamic routing</b> <div v-for="item in items" :key="item.id"> <b>{{ item.id }}.</b> &nbsp;&nbsp;&nbsp; <rou ...

`How can I make Vue listen for events?`

After making corrections to fix an unreported syntax error (check comments), the code now functions as intended. I am facing an issue with my event handler not triggering in the Vue code below. There are two components, named posts and post, along with a ...

Tips for eliminating the trailing slash from the end of a website article's URL

I've recently delved into learning Gatsby, and I've encountered an issue with the Open Graph tag in my project. The og:image is displaying a different image than the intended thumbnail for the article. Here's an example article - . When try ...

The .prepend() method receives the variable returned by ajax and adds it

I'm facing a challenge with adding a dynamic select box to a string within my .prepend() function. The options in the select box are subject to change, so hard coding them is not an option. To tackle this issue, I am using an AJAX call to construct th ...

django, the X-CSRFToken in the request header is improperly configured

Essentially, I have managed to successfully send a CSRF token to the frontend and store it in the cookie section of the application tab within the developer console of the browser with this code: @method_decorator(ensure_csrf_cookie) def get(self, ...

What is the best way to update a CSS href using window.open with JavaScript?

I am trying to dynamically change the CSS href by using window.open in JavaScript. <a class="cssButton" id="Launch" target="_blank" data-baseref="Example/index.html?" href="Example/index.html?" >Launch Example</a> I want to transform it into: ...

Encountering an issue with Angular directive attributes

I am attempting to create an angular directive that will extract a substring from a passed-in attribute. Below is the code I have written: HTML: <body ng-controller="MainCtrl"> <div><substring message="This is a test."></substri ...

How can JavaScript transform Unicode strings?

<i class="icon">&#xe672;</i> This code will display an icon like this: > However, when I render it in Vue: <i class="icon">{{a}}</i> a = '&#xe672;' The result is  It displays as a string! ...

Issue encountered with Electron's Puppeteer: "equire is not defined" and "__dirname is not defined"

I'm currently in the process of building an Electron application with the help of the Vue CLI package from npm. However, while using puppeteer, I encountered the following error message. Uncaught ReferenceError: __dirname is not defined at eval (w ...

Can you verify that the client's date and time locale are accurate in JavaScript before proceeding with processing?

For my application, I am seeking the current locale datetime. However, before retrieving the date, it is crucial to verify that the local date and time are accurate. If the user has adjusted the date and time incorrectly on their machine, I must prompt a ...

Sending a POST request to a PHP file in React: A Step-by-Step Guide

Just starting out with reactjs and trying to figure out how to send an ajax request to a server (php file). Here's the structure of my project: check it out here src/index.js import React from 'react'; import ReactDOM from 'react-dom& ...

What is the appropriate content-type to use when sending AJAX POST data?

Having an issue sending base64 image data using ajax post. I suspect the problem lies with the Content-Type value, as I have tried using application/json, text/json, and image/jpeg without success. Javascript function sendFormData(fD) { var urls = fD ...

CSS Only Sidebar Dropdown (without using Bootstrap)

I want to create a sidebar with collapsible dropdown options and smooth animations using only pure css/js/html/jquery, without relying on bootstrap like I did in the past. Here is an example of what I created previously with bootstrap: Now, as a challenge ...

Record the actions emitted by child components

I am struggling to respond to an action emitted by a child component. The child triggers an event/action called init. I try to listen for this event in the parent component's events mapping. However, the callback function never executes, leading me to ...

Creating interactive popups using Web Map Service (WMS) with the

I am looking for a way to make a leaflet map loaded from a geoserver interactive by displaying popups with information. Can someone provide a solution using jsfiddle to help me understand? I am struggling to figure out how to achieve this. Essentially, I w ...

Having trouble displaying the output on my console using Node.js

Hey there, I'm new to this community and also new to the world of nodejs technology. I have encountered a problem that may seem minor to you but is quite big for me. Here's what's going on: In my code snippet, I want a user to input 3 value ...

Navigating the missing "length" property when dealing with partial functions generated using lodash's partialRight

I've been utilizing MomentTimezone for time manipulation within the browser. My development stack includes TypeScript and Lodash. In my application, there is an accountTimezone variable set on the window object which stores the user's preferred ...

Customizing upload directories in elfinder for dynamic path generation

In my CodeIgniter project, I am trying to configure elfinder to have a dynamic upload path for each unique ID. The folder structure I am working with is as follows: Below are my elfinder settings: $idce = $_GET['id_c']; $client_code = $this- ...