Error: Unable to access value of 'amount' because it is undefined

After converting the Django models into a JSON data object and attempting to access it in Javascript, I ran into an issue. Specifically, I am unable to retrieve a field from the object and assign it to a text box.

The JSON object that is returned appears as follows:

[{"model": "inventory.inventory","pk": 1, "fields":
{"product": "nice", "title": "Asus", "amount": 56000}},
{"model": "inventory.inventory", "pk": 2, "fields":
{"product": "nice", "title": "Lenovo", "amount": 55000}}]

Here is the snippet of javascript code that I am currently using:

    <html>....{{ data|json_script:"hello-data" }}....
    <script type="text/javascript">
    const data = JSON.parse(document.getElementById('hello-data').textContent);

    document.getElementById('id_line_one').onchange = function(){
        var line_one=document.getElementById('id_line_one').value;
        var id=line_one-1;
        document.getElementById('id_line_one_unit_price').value = data[id].fields.amount;
    };

</script>....</html>

https://i.sstatic.net/g8dFv.jpg When selecting a title from the dropdown list, the return value is its primary key, known as product_number. My objective is to fetch the associated amount for that particular product based on the selected product_number. Given that objects in JSON are indexed starting from 0(?), I initially believed my code logic was accurate. However, lacking expertise in this area, I suspect I may have overlooked a simple mistake. Any suggestions on how I can display the amount of the object in the unit price text box upon selecting a title from the dropdown list would be greatly appreciated. Thank you!

views.py

@login_required
def add_invoice(request):
  form = InvoiceForm(request.POST or None)
  data = serializers.serialize("json", Inventory.objects.all())
  total_invoices = Invoice.objects.count()
  queryset = Invoice.objects.order_by('-invoice_date')[:6]

  if form.is_valid():
    form.save()
    messages.success(request, 'Successfully Saved')
    return redirect('/invoice/list_invoice')
context = {
    "form": form,
    "title": "New Invoice",
    "total_invoices": total_invoices,
    "queryset": queryset,
    "data": data,
}
return render(request, "entry.html", context)

Answer №1

It would be more beneficial in your situation to utilize array.find()

document.getElementById('id_line_one').onchange = function(event){
        let elementInData = data.find((item) => item.pk == event.target.value);
        document.getElementById('id_line_one_unit_price').value = elementInData && elementInData.amount ? elementInData.amount : 0;
    };

Alternatively, you can structure your data as a dictionary:

data = serializers.serialize("json", Inventory.objects.in_bulk())

Following that, you will need to incorporate the following JavaScript code:

data = JSON.parse(document.getElementById('hello-data').textContent);

// data is {1: {"model": "inventory.inventory","pk": 1, "fields":
{"product": "nice", "title": "Asus", "amount": 56000}}, ...}

Subsequently, you can access each element by its key:

document.getElementById('id_line_one_unit_price').value = data[event.target.value].fields.amount 

Eliminating the need for arr.find().

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

Guide on uploading files and data simultaneously by leveraging ajax, jquery, and spring mvc

How can I use ajax, query, and Spring MVC to upload data along with a file? Below is my modal pop-up, could someone help me with this? <!-- Modal --> <div id="fileUpload" class="modal fade" role="dialog"> <d ...

What is preventing ShowViaLink() from functioning properly in Firefox and Internet Explorer?

I am facing an issue with my webpage where the navigation does not work on Firefox or IE, but it works perfectly fine on Chrome. I suspect that the problem lies in this code, as when I made changes to it, the navigation stopped working on Firefox & IE: ...

The previous and next arrows do not have a looping feature

I have a collection of 10 HTML pages stored in a folder called PROJECTS. Everything is functioning properly, except for the prev and next arrow navigation buttons. The issue arises when navigating to the last page (e.g., projectPage_10.html) from my Projec ...

Retrieving the failing field in Mule through JSON Schema Validation

Using APIkit in Mule with RAML 0.8 and a JSON schema, the following setup is in place: { "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "properties": { ...

Encountered an error while attempting to complete the 'send' action with 'XMLHttpRequest'

I am currently developing a Cordova application that makes use of ajax. Everything works perfectly during debugging, but once I build the release version, I encounter this error: {"readyState":0,"status":0,"statusText":"NetworkError: Failed to execute &ap ...

What is a way to automatically run a function at specific intervals in PHP, similar to the setTimeout() function in JavaScript?

I have a JavaScript code snippet that looks like this: setTimeout('$.ajaxCall("notification.update", "", "GET");', 1000); Now, I want to execute the following PHP function every 1000 milliseconds, similar to the above JavaScript code: $notific ...

Tips on creating horizontally aligned buttons with full width

Currently, I am facing an issue while attempting to create three equal-sized buttons laid out horizontally. However, what I have accomplished so far is displaying three full-width buttons stacked vertically. Here's the code snippet: <section class= ...

Trouble uploading an audio blob as a base64 string using Google Drive API with the drive.files.create method - File ID could not be located

My current challenge involves sending an audio blob to a specific Google Drive folder. To accomplish this, I convert the blob into a file before initiating the transfer process. However, I have encountered an error from the beginning: Error: File not fo ...

Attempting to develop a next.js web application using Vercel has hit a roadblock for me. Upon running the "vercel dev" command in the terminal, an error message is

vercel dev Vercel CLI 28.5.3 > Creating initial build node:events:491 throw er; // Unhandled 'error' event ^ Error: spawn cmd.exe ENOENT at ChildProcess._handle.onexit (node:internal/child_process:285:19) at onErrorNT (nod ...

The result returned by Array.isArray is false

As someone diving into the world of javascript and currently unpacking destructuring, I stumbled upon a puzzling snippet that sparked a question in my mind. After some editing, my code was identified as an array by the console, which left me scratching my ...

Troubleshooting Vue.js: Understanding the Issue with Debonuce Function and Arrow Functions

Here is a custom debounce function I implemented: function customDebounce(func, delay = 1500) { let timeout; return function (...args) { if (timeout) clearTimeout(timeout); let context = this; timeout = setTimeout(function () { func.a ...

What's the reason behind the Flow error message indicating that the variable is not recognized as a string

Here is the code snippet causing an issue (I suspect it may be a typing error rather than a problem with the actual download code): ... TokenService.getToken(id).then(result => { const { read } = result; if (typeof read === 'string') { ...

How come the `setAllSelected` function does not activate the `listbox.valueChange` events, and what can be done to make it happen?

How come setAllSelected is not triggering the emission of listbox.valueChange? What steps can be taken to ensure that it does emit? import { Component, ViewChild } from '@angular/core'; import { CdkListbox, CdkOption } from '@angular/cdk/lis ...

Identifying when a user closes a tab or browser to trigger a logout in JavaScript with Vue.js using the Quasar framework

Is there a way to trigger the logout function only when the tab or browser is closed, and not when the page is refreshed? I attempted the following code example, which successfully triggers the logout on tab close but also logs out when the page is ref ...

The function this.listCatModel.push is not a valid operation

I have a dropdown that I want to populate using the following code: this.categoryService.GetListItem(this.GetAllcatListUrl).subscribe(data=>{ this.listCatModel=data, this.listCatModel.push({ id:0, name:'Main Category', parent ...

Can you provide instructions on utilizing WYSIWYG for real-time label editing?

I am currently developing an online survey creator. The structure of a Question entity is as follows: [Question] int QuestionId { get; set; } int QuestionNumber { get; set; } String QuestionText { get; set; } QuestionType QuestionType { get; } When prese ...

Hold off on compiling the Angular directive template until the function has finished executing

I created an angular directive that dynamically displays an image on my webpage based on the value in a querystring within the URL: app.directive('myDirective', function(myService) { return { restrict: 'A', replace: ...

Parse the JSON file and assign the arrays to your GO variables

I've been given the challenging task of migrating my project from Python to Go, but I've hit a roadblock that's been consuming hours of my time. Within my project, there exists a file named data.json which houses the following information: ...

The material UI Paper component appears to be extending beyond the boundaries of the background image

I have configured the Grid component to occupy 6 on small/medium screens for a side-by-side layout and 12 on xs screens for each item. While everything looks fine in the computer view, I am facing an issue with the mobile view where the paper component is ...

Error: The JSON data contains an unexpected token 'm' in the "module.exp" which is causing a SyntaxError

$ npx json-server --version 1.0.0-alpha.23 $ node -v v20.12.0 $ ls generate.js node_modules package.json package-lock.json public README.md src I've been attempting to launch a React project locally from a GitHub repository. Despite installing ...