0

Basically I'm trying to pass an json-array via onclick to a function

<button
  onclick='showAccountOverviewModal("<%= accounts[j].name %>", `<%= accounts[j].bills%>`)'>
  Click Me
</button>

But, when I try to parse the string via JSON.parse, I realize, that neither the keys, nor the values have quotation marks. Is there any 'good' way to fix this or do I need to use regular expressions?

Best regards

EDIT

This is the corresponding function:

function showAccountOverviewModal(accountName, accountBills) {
  $("#accountModalOverviewTitle").text(accountName);
  accountBills = JSON.parse(accountBills);
  console.log(accountBills);
  accountBills.forEach(bill => {
    console.log(bill);
  });
}
kushdilip
  • 7,606
  • 3
  • 24
  • 30
Lenny Will
  • 549
  • 1
  • 4
  • 11
  • Could you show some of the `showAccountOverviewModal` function? It would be helpful to know how those arguments are used. What are you using to parse out the `<%=` constructs? – Tom Holmes Jun 19 '19 at 23:05
  • @TomHolmes Edited the code to provide more information – Lenny Will Jun 20 '19 at 06:54
  • You have some ASP or EJS or something from which you are generating HTML with embedded JavaScript. **Look at the generated HTML**. Figure out what is wrong with it, then worry about how to change the ASP/EJS/whatever to make it generate what you really need. – Quentin Jun 20 '19 at 08:22

2 Answers2

1

It looks like you you may be passing a javascript array (already parsed) as opposed to a JSON array (a string representing the array). If so, prior to JSON.parseing it, running

console.log(Array.isArray(accountBills))

should print true. If it is actually JSON, that would print false and running

console.log(typeof accountBills)

would print string.

If it is an array, then you don't need to parse it, and removing the JSON.parse line should make it work as expected.

Tom Holmes
  • 1,196
  • 8
  • 11
1

ill rewrite your code using data-* attribute. you can disregard if you dont want this approach.

html

<button class="showaccountmodal" 
data-accountName="<%= accounts[j].name %> 
data-bill="<%= accounts[j].bills %>">Click Me</button>

jquery

$(".showaccountmodal").on('click', function() {
var accountname = $(this).data('accountName');
var bill = $(this).data('bill');
console.log(accountname);
console.log(bill);
 accountBills.forEach(bill => {
    console.log(bill);
  });
} );

also here's a reference for storing json object in html Store JSON object in data attribute in HTML jQuery

Julius Limson
  • 526
  • 9
  • 29