-3

I have a simple var with some strings that I convert to a json object. I would like to have an input field for the persons name and then add the text.

Currently I have this

var text = '{"students":[' +
'{"firstName": "Brendan","lastName":"Skousen" },' +
'{"firstName":"Scooby","lastName":"Doo" },' +
'{"firstName":"Your","lastName":"Mom" }]}';

and I have a var for my input

var first = document.getElementById('first').value;

So I would like to have the var text work like this:

var text = '{"students":[' +
'{"firstName": first,"lastName":"Skousen" },' +
'{"firstName": first,"lastName":"Norman" },' +
'{"firstName": first,"lastName":"Coatney" }]}';

You can see the full code at: http://codepen.io/bskousen/pen/xbPLew

Brendan
  • 387
  • 1
  • 5
  • 16

2 Answers2

0
var text = '{"students":[' +
'{"firstName": ' + escape(first) + ',"lastName":"Skousen" },' +
'{"firstName": ' + escape(first) + ',"lastName":"Norman" },' +
'{"firstName": ' + escape(first) + ',"lastName":"Coatney" }]}';

Using escape from here.

Community
  • 1
  • 1
StenSoft
  • 9,369
  • 25
  • 30
-1

To make it work the way you use it in your example you would have to use a template engine and add some extra characters around the variable depending on the engine you went with. I think concatenation would be easiest for your case

var text = '{"students":[' +
'{"firstName": ' + first + ',"lastName":"Skousen" },' +
'{"firstName": ' + first + ',"lastName":"Norman" },' +
'{"firstName": ' + first + ',"lastName":"Coatney" }]}';