-2

I'm a coding novice, trying to learn! I have passed a query parameter into a JavaScript variable using the below:

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

And would now like to pass it into JSON, within the below div

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

Such that my parameter will ultimately populate on the review form.

Any help much appreciated!

I initially tried passing the JavaScript variable into the field before realising it was JSON.

Aleksandar
  • 844
  • 1
  • 8
  • 18
joelinit
  • 39
  • 6
  • Warning: You haven't shown where your JavaScript code above is, but **if** it's at global scope, it's important to use `let name = ___` instead of `var name = ___` because the latter will try to set the window's `name` property. (Or use a name other than `name`. Or better yet, don't put your code at global scope, use [modules](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules).) More: https://stackoverflow.com/questions/10523701/using-the-variable-name-doesnt-work-with-a-js-object – T.J. Crowder Apr 04 '23 at 11:19

1 Answers1

0

I'm going to assume that the target div already exists in the page by the time your JavaScript code runs, and it is uniquely-identifiable via an id or a CSS selector. If so:

  1. Locate the element (via document.getElementById if you're using an id, via document.querySelector if not).
  2. Create the JSON by creating an object with name as its firstName property, then using JSON.stringify to get the JSON for that object: JSON.stringify({firstName: name}).
  3. Set the data-prefix attribute via setAttribute

For example, if this is the only element with the class review-form (or the first one):

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

You could also use the element.dataset object instead of the element.setAttribute method, but for a beginner, I'd stick with the simple setAttribute for now.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875