The process of embedding variables within a JSON Array function in JavaScript

As a newcomer to JavaScript, I am facing an issue while trying to create a simple program. I am attempting to store the variables 'name', 'document', and 'code' inside the JSON array called 'records'.


var records = [];
var code = 1;

function save() {
    var name = document.getElementById("pName").innerText;
    var doc = document.getElementById("pDocument").innerText;
    
    var record = {
        code: 0,
        name: "",
        sex: ""
    };
    
    record.push(code, name, doc);
}  

Answer №1

To make adjustments to the salvar() function, you can specify each value of your "registro" variable like so:

var registro = [{
    codigo: codigoValue,
    nome: nomeValue,
    sexo: ""
}];

After that, use the push() function to add "registro" into the "registros" array. The revised code would look like this:

var registros = [];
var codigoValue = 1;
function salvar() {
    var nomeValue = document.getElementById("pNome").innerText;
    var documento = document.getElementById("pDocumento").innerText;
    var registro = [{
        codigo: codigoValue,
        nome: nomeValue,
        sexo: ""
    }];
    registros.push(registro);
}

Answer №2

When working with arrays in JavaScript, it's important to pay attention to the property/value structure. In your code snippet, you have assigned values to a variable called registro instead of registros.

Furthermore, the registros variable seems to be unused in your code.

To correct this issue, follow these steps:
  1. First, create an array variable named registros
  2. Next, define a function called salvar
  3. Inside the salvar function, create an object that will store your values. For example, you can create an object with a property named "nome" and assign it the value fetched from document.getElementById("pNome").innerText.
  4. Finally, push the created object into the registros array
var registros = [];
var codigo = 1;
function salvar() {
    var nome = document.getElementById("pNome").innerText;
    var documento = document.getElementById("pDocumento").innerText;
    var obj = { nome, documento, caodigo}

    registros.push(obj);
}

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 include a CSS file path in a link tag from an npm package

I have recently installed a package using npm. npm install lightgallery Now, I am trying to fill the href attribute of a link with the css file directory of this package. Here is what I have so far: <link rel="stylesheet" href="/node_mod ...

Evaluating Vue with AVA - The key is in the whitespace

Currently, I am engrossed in a Laracast Episode about Vue Testing with AVA. Everything has been going smoothly so far, but now I have encountered an intriguing bug. This is my notification.js: import test from 'ava'; import Notification from &ap ...

Setting the default value for drop-down menus in jqGrid form editing

I have a data object with 3 attributes: ID Abbreviation Description In my jqGrid setup, I've configured the grid to display the Abbreviation. During editing (using the Form Edit feature), I populate the dropdown list with ID/Description pairs usin ...

Images showing Strava heat maps retrieved through API

Check out this amazing heatmap created by Strava! I'm curious about how they were able to achieve this - it seems like they are using the API to request overlay images based on the network tab. I have my own geo data, but I'm wondering how I can ...

When incorporating a JS React component in TypeScript, an error may occur stating that the JSX element type 'MyComponent' is not a valid constructor function for JSX elements

Currently, I am dealing with a JavaScript legacy project that utilizes the React framework. Within this project, there are React components defined which I wish to reuse in a completely different TypeScript React project. The JavaScript React component is ...

Send in the completed form with your chosen preferences

Is there a way for me to submit a form with the selected option? My backend code is set up to work when using inputs: <input id="id_value_0" name="value" type="radio" value="1" /> <input id="id_value_1" name="value" type="radio" value="2" /> ...

Why does the final value appear when passing an incrementing counter as a prop to multiple React Components created in a loop?

I am currently unraveling the concept of closures in JavaScript. Within this code snippet, I am cycling through the values of the 'items' array using a foreach loop. I have defined a let variable named "count" outside the scope of the loop. Afte ...

Steps for generating a div, link, and image that links to another image using Javascript

Hey there, I have a cool picture to share with you! <img src="cards.png" id="img"> <!--CARD PICTURE--> Check out what I want to do with it: <div class="container_img"> <img src="cards.png" id="img"> <!--CARD PICTURE--> ...

Alerts in online software when there is a modification in the database

I am working on a project to create a web application that needs to display notifications, like the ones you see on Facebook, whenever there is a new update in the database. I could use some assistance with implementing this feature. Are there any third- ...

Issue with jQuery validation plugin is that the select element is not being properly validated

The jQuery validation plugin I'm using (http://bassistance.de/jquery-plugins/jquery-plugin-validation/) is functioning properly on most elements, but there are 2 select boxes where it's not working. You can see an example of one of these problema ...

Querying Quandl API with Node.js using HTTPS Request

My current project involves developing a web service using IBM Bluemix for a school assignment. The core requirement for my project is to retrieve JSON data from two distinct APIs to be integrated into the project's functionality. The initial API re ...

Is there a reliable method to verify the correctness of an HTML input?

I'm currently developing a quiz using <input type="text"> and <input type="number">. I've noticed that relying on numerous if / else statements in my code is proving to be highly inefficient due to the sheer amoun ...

Sending an Angular scope variable to JavaScript

I am working with an angular scope variable that is being used in ng-repeat. My goal is to create a chart that starts from a specific date, ends at another date, and includes a marker for the current day. I am utilizing loader.js for drawing the charts in ...

Using ElectronJS requires the usage of the import keyword to load ES Modules

I've recently delved into Electron development by exploring the Electron Docs. I opted for ES6 syntax with import/export, while the documentation showcased the use of require. To align with ES Module standards, I updated my package.json file with typ ...

Obtaining the value of a JavaScript confirm popup in C#.NET

I am trying to implement a javascript confirm popup that returns a value from the code behind. When the user selects the ok button on the confirm popup, certain code will execute, and if they select cancel, different code will run. Is there a way to retri ...

How can I decrease the time intervals between my JSON requests?

Currently, I am utilizing this specific script to interact with numerous endpoints at Seatgeek. In order to prevent being throttled by Seatgeek due to excessive usage, I need guidance on how to adjust the time gap between each endpoint call. My intention ...

encountering issue alerts when using the MUI TextField module alongside the select function

Encountering an error in the MUI console: children must be provided when using the TextField component with select. <TextField select id="outlined-basic" label="User Name" name="user" size="small" {...teamForm.getFieldProps("user")} erro ...

I am looking to incorporate a dropdown feature using Javascript into the web page of my Django project

According to the data type of the selected column in the first dropdown, the values displayed in the columns of the second dropdown should match those listed in the JavaScript dictionary below, please note: {{col.1}} provides details on the SQL column data ...

Customizing the styling of buttons in Highcharts is disabled when in full screen mode

I've integrated highcharts into my Angular application and included a custom button inside the chart to navigate users to another page. However, I encountered an issue when trying to fullscreen the chart using the export menu. The position of the cus ...

How to achieve multiplication in Javascript without utilizing the * operand

Challenge 1 Criteria: This problem involves working with two positive integers N and M. Outcome: Upon completion, the function should output the result of multiplying N and M. For instance, if you input 5 and 8 into the function, it should calculate and ...