What is the best way to transfer a JavaScript variable to a JSON format?

Hey there! I'm diving into the world of coding and eager to learn. Recently, I successfully passed a query parameter into a JavaScript variable using the following code:

const queryString = window.location.search;
console.log(queryString);
const urlParams = new URLSearchParams(queryString);
var name = urlParams.get('id')

Now, my goal is to transfer this information into JSON within the designated div below:

<div 
 class="review-form" 
 data-site-uuid="xxxxxx" 
 data-form-uuid="xxxxxx" 
 data-prefill='{"firstName":name}'
></div>

This way, the parameter will seamlessly populate on the review form as intended. Any tips or guidance would be greatly appreciated!

I initially attempted to insert the JavaScript variable directly into the field, only to realize it required JSON formatting.

Answer №1

Assuming that the specified div is already present on the webpage when your JavaScript code executes, and can be uniquely identified by an id or CSS selector, you can follow these steps:

  1. Find the element using document.getElementById if it has an id, or document.querySelector otherwise.
  2. Construct a JSON object with a property named firstName, then use JSON.stringify to convert this object into a JSON string:
    JSON.stringify({firstName: name})
    .
  3. Set the value of the data-prefix attribute using setAttribute

For instance, if the element with the class review-form is unique (or the first one):

const element = document.querySelector(".review-form");
const json = JSON.stringify({firstName: name});
element.setAttribute("data-prefix", json);

Alternatively, you can utilize the element.dataset object in place of element.setAttribute method, but starting out, it's recommended to stick with the straightforward setAttribute.

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

Compilation of Angular 6 project is failing due to error TS1005: Expected ',' instead of the symbol used

I keep encountering an error message whenever I try to compile my code. ERROR in src/app/form/form.component.ts(22,39): error TS1005: ',' expected. Below is the snippet of code where the error is pointing: import { Component, OnInit } from &ap ...

No output from JavaScript loop when trying to print an array

I've been looking all over the place and haven't been able to find a pure JavaScript solution for my problem that I can implement into my code. The issue involves a script that is meant to display an array of images, but currently it only display ...

Utilize Google Maps to receive directions to a specific destination and discover current traffic conditions along the route using their comprehensive API

I am currently working on implementing the Google Maps direction identifier functionality with traffic details. However, I am able to obtain directions but not specific traffic details for a selected path; it seems to apply overall traffic data instead. ...

Unable to retrieve Objects from JSON

Here is a JSON object I received: [{"model": "pricing.cashflow", "pk": 1, "fields": {"value": 4.0, "date": "2016-09-09"}}, {"model": "pricing.cashflow", "pk": 2, "fields": {"value": 3.0, "date": "2016-09-01"}}, {"model": "pricing.cashflow", "pk": 3, "fiel ...

Utilizing jQuery to send an Ajax GET request for a JSON file

Recently I have begun delving into the world of jQuery and Ajax, attempting to utilize both technologies to retrieve a JSON FILE. Below is the structure of the file: [ { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": f ...

Challenges arise when trying to coordinate scrolling movements between a canvas element and the remaining content on the webpage

I'm currently stuck on a project involving a Three.js canvas with OrbitControls for interactive 3D visualization. The main issue I'm facing is the lack of synchronization between scrolling within the canvas and the rest of the page content. Whil ...

Learn the process of extracting the first array object from JSON using Python

I'm facing an issue where I have a JSON file that needs to be converted into CSV. However, the JSON file contains a JSON object which is an array, and all the attributes are within that array. The code I currently have only converts the first object i ...

The Handlebars template remains blank, failing to show any data or error messages

//////////////////////////////////// // Function to append items // ////////////////////////////////// function addItems(data) { var template = document.getElementById('items').innerHTML; var handlebarsTemplate = Handlebars.compile(tem ...

Changing a numeric string into a number within an Angular 2 application

Looking for advice on comparing Angular 2 expressions. I have an array of data stored as numeric strings in my database and I need to convert them to numbers before applying a condition with ngClass for styling purposes. Any suggestions on how to perform ...

What steps should I take to make my alert vanish?

I'm facing a challenge with an alert I created using Bootstrap in my Django project. Despite following instructions from the bootstrap website, I can't get the alert to disappear when I click on the x button. The errors I encountered are: Uncau ...

Looking to implement URL navigation based on a selected value from a dropdown menu when the onClick button is pressed

I am struggling with getting the Go Button to navigate to a specific URL like "&age=10" without selecting it. I require assistance with creating code that will allow me to redirect to the URL with post URL variables for my WordPress site. ...

Using JavaScript to transform base64 encoded strings into images

I'm currently working on an app using Titanium and I have a base64 string that I need to convert into an image from JSON data. Any assistance you can provide would be much appreciated. Thank you! ...

How to correctly structure a JSON object in Swift 3

I'm encountering a problem with formatting my JSON object on my Node.js server. My API is configured to accept a JSON object and save it in a database. Everything works fine when I send a POST request using Postman, but I run into an unusual error whe ...

calculating the rotation angle from the origin to a vector within a three-dimensional space using three.js

I am working with a vector in three-dimensional space. Is there a method to determine the angle of rotation from the origin to this vector on each axis? For example, if the vector is located at x=6, y=-10, z=20, what angle does the vector make with resp ...

React - Programmatically adjust state without specifying key field in advance

With ES6, the ComputedPropertyName feature allows for using variables as keys for objects in JavaScript. This feature opens up possibilities such as dynamically setting state values. However, most examples of dynamic state setting involve hardcoding the na ...

Can you help me troubleshoot an issue I am facing with the expand table in Angular 9 and JS? I am getting an

Here you can find the code demonstration and behavior: No extensive explanation is necessary. Check out the StackBlitz demo by clicking on the first row to view its details. Then, click on the second row to see how the details from the first row are repl ...

Calculate the total of the temporary information entered into the input field

I'm totally new to all of this and definitely not an expert, but there's something that really bothers me. I found a website where you have to complete a captcha to log in. It goes like this: <input type="text" class="form-contr ...

changing the core JavaScript of a keyboard plugin

To access the demo, click on this link: . You can find the main javascript file at https://raw.githubusercontent.com/Mottie/Keyboard/master/js/jquery.keyboard.js. Is there a way to switch the positions of the accept and cancel buttons? ...

Having trouble binding component property in VueJS with TypeScript?

Why is my component property not binding when I set the related component attribute to a value? Even when inspecting with Vue devtools or outputting the value into the HTML, it remains at the default value set on the component. I tried setting a string at ...

Ways to utilize $document within a Modal

I'm struggling to utilize the $document in the modals controller. Is there a proper way to pass it in? Just using document is not allowed according to our Angular project guidelines. How I call the modal: var modalInstance = $uibModal.open({ t ...