Having issues with adding elements to an array object in JavaScript

I've got some HTML code that looks like this:

HTML:

 <INPUT TYPE=CHECKBOX NAME="clcik" onClick="add('1234','blah')" />
 <input type="hidden" id="project" value="" />

JS:

    function add(obj1 , obj2){
    var jsonArray = [];
    var jsonObj = { product_id : obj1 , name : obj2 };
    jsonArray.push(jsonObj);
    var field = document.getElementById('project');
    field.setAttribute('value', JSON.stringify(jsonArray));
    alert(field.getAttribute('value'));
    }

I'm attempting to set a value and then retrieve it again for testing purposes, but I'm not seeing any changes. I'm puzzled as to where I may have gone wrong...?

Answer №1

Perhaps you overlooked the step of storing the stringify result in the stringData variable, causing a JavaScript error before reaching the line where you attempt to alert the value.

jQuery does not provide JSON or JSON.stringify, so you need to include the json2 library on the page if the browser does not natively support it.

Here is a modified code snippet:

function add(obj1 , obj2){
    var jsonArray = [];
    var jsonObj = { product_id : obj1 , name : obj2 };

    jsonArray.push(jsonObj);
    var stringData = JSON.stringify(jsonArray);

    var field = document.getElementById('project');

    field.setAttribute('value', stringData);
    alert(field.getAttribute('value'));
}

Below is the code for removing an element from an array based on a specific request:

var newArray = [], productIdToRemove = "1234";
$.each(jsonArray, function(){
   if(this.product_id != productIdToRemove){
      newArray.push(this);
   }
});

//Now newArray will no longer contain '1234'

Answer №2

Adjustment

Convert jsonArray to a string using JSON.stringify()
// Instead of
var stringData = JSON.stringify(jsonArray);

Resolved other issues with the code snippet: http://jsfiddle.net/mattball/qWCwa/7/

Answer №3

One thing to note in your sample is that you haven't initialized the variable stringData.

Answer №4

Access the "value" property of the input element directly instead of using getAttribute and setAttribute methods.

Answer №5

After making the necessary adjustments to assign stringData, everything seems to be functioning correctly:

function combineObjects(obj1 , obj2){
    var jsonArray = [];
    var jsonObj = { product_id : obj1 , name : obj2 };
    jsonArray.push(jsonObj);
    var stringData = JSON.stringify(jsonArray)
    var field = document.getElementById('project');
    field.setAttribute('value', stringData);
    alert(field.getAttribute('value'));
}

combineObjects(1, 2);

You can view the updated code in action here: http://jsfiddle.net/jfriend00/HNuak/.

Just a heads up, if you run into any issues, using tools like Chrome or Firefox debuggers can help pinpoint and resolve errors more effectively.

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

Is there a way to switch up the dropdown chevron using only CSS after a click?

Is there a way to change the appearance of dropdown arrows using only CSS and animations when clicked on? I attempted the following method: body { background: #000; } #sec_opt select { /* Reset */ -webkit-appearance: none; -moz-appearance: n ...

Generating a JSON String on iOS

My iOS Application is sending a POST request to a server, and I need to include metadata in JSON format in the request body. Here is the JSON structure I am trying to send: { "snippet": { "title": {VIDEO TITLE}, ...

Tips for performing an update in AWS DynamoDB with Node.js

I have created a function to update data in a DynamoDB table const updateData = async (req, res) => { try { const { existingData, updatedData } = req.body; console.log(existingData, updatedData ); UPDATE({ TableName: "todos" ...

Guide on retrieving simplejson in Python

As a beginner, I am currently delving into a Python project that involves working with json data. My aim is to retrieve information by calling an object ("object.json()"). The catch is that I am restricted to importing simplejson and not allowed to impor ...

Display a loader while waiting for an API call to complete within 5 seconds using Angular and RxJS operators. If the API call takes longer

We are actively working to prevent user blockage during file uploads by implementing a method in Angular using RxJS. How can I display a toastr message and hide the loader if the API does not complete within 5 seconds? uploadFile() { this.service.uploa ...

Can JavaScript be used to modify the headers of an HTTP request?

Can JavaScript be used to modify or establish HTTP request headers? ...

It is advised not to use arrow functions to assign data when fetching API data with axios in Vue.js 2

Trying to retrieve data from a URL using Axios in my Vue app is resulting in the error message: Error: Arrow function should not return assignment Complete error message: Error: Arrow function should not return assignment (no-return-assign) at src\co ...

Using $state.go within an Ionic application with ion-nav-view may cause unexpected behavior

I recently started working on an Ionic Tabs project. I have a button called "initiateProcess" that triggers some operations when clicked using ng-click. Within the controller, it performs these operations and then navigates to a specific state (tab.target) ...

Looking to showcase a loading gif inside a popover before swapping it out with ajax-generated content

My goal is to populate a popover with content using ajax requests. Here's the setup: $('.openMessagePopover').popover({ html: true, content: function() { $threadId = $(this).data('id'); return getContent($threadId) ...

Attempting to route a selector, yet on the second attempt, the entity is successfully transferred

I am currently working on developing a function that will switch the image every half second for 10 iterations. During the final iteration, the image src will be set to the actual value. Everything seems to work fine for the first loop, however, when the s ...

a single button with dual functionalities

I am new to the development field and have a question about jQuery. I want a single button to perform two different actions. For example, let's say we have a button labeled Pause/Resume. When I click on the button, it should first display "Pause", and ...

Stylish Navigation Menu Logo/Site Name

Currently in the process of upgrading my website and I have my website name included as part of my menu, as opposed to a logo. This has been an easy solution that has worked well for me. For mobile screens, the template I purchased includes a slicknav men ...

What is the reason for sending back an array with no elements in AJAX

I am facing a perplexing issue where my function is returning an empty array when it should contain values. This has me scratching my head, as initially the array 'storearray1' does contain values, but upon subsequent usage, it appears empty. I&a ...

Using jquery.ajax triggers a non-object exception

Hi there, I'm working with this jQuery code: var input = JSON.stringify(data); // output: [100.100] var lines = input.split('.'); var vari1 = lines[0]; // output: [100 var vari2 = lines[1]; // output: 100] var data = {'x':vari1 ...

Combine multiple arrays in JavaScript into a single array

Here is the array I am working with: array = ['bla', ['ble', 'bli'], 'blo', ['blu']] I need to transform it into this format: array = ['bla', 'ble', 'bli', 'blo', &a ...

JavaScript: Retrieving the following element from the parent container

Is there a way to prevent the next element within the parent tag from being enabled or disabled based on a certain condition? HTML: <span> <input type="checkbox" onchange="toggleInput(this)"> </span> <input type="text" ...

How to maximize efficiency by utilizing a single function to handle multiple properties in Angular

I have 2 distinct variables: $scope.totalPendingDisplayed = 15; $scope.totalResolvedDisplayed = 15; Each of these variables is connected to different elements using ng-repeat (used for limitTo) When the "Load More" button is clicked (ng-click="loadMore( ...

What is the best way to eliminate "?" from the URL while transferring data through the link component in next.js?

One method I am utilizing to pass data through link components looks like this: <div> {data.map((myData) => ( <h2> <Link href={{ pathname: `/${myData.title}`, query: { ...

Are there any alternative solutions to the onunload event in Chrome, or any other ways to achieve the

After extensive searching for a solution to this issue, including scouring Google Chrome support sites and the Chrome Bug Issues page where the problem has not yet been resolved. Currently, I find myself in a situation where I need to use the onload or onb ...

Mongoose and MongoDB in Node.js fail to deliver results for Geospatial Box query

I am struggling to execute a Geo Box query using Mongoose and not getting any results. Here is a simplified test case I have put together: var mongoose = require('mongoose'); // Schema definition var locationSchema = mongoose.Schema({ useri ...