-1

I have this code from my JS File:

var formStr = "<h5>How many books?:</h5><input type='number' id='bookinput'
value='' /><input type='button' value='submit' onclick='addbook();' />"
infowindow = new google.maps.InfoWindow();
infowindow.setContent(formStr);
infowindow.setPosition(location);
infowindow.open(map);

JS variable formStr has html code as you can see above. I want to be able to put JS variables into this without moving the HTML out of my JS file. Something like:

var objectType='book';
var formStr = "<h5>How many *objectType*?:</h5><input type='number' id='bookinput' value='' /><input type='button' value='submit' onclick='addbook();' />"
MRDJR97
  • 818
  • 2
  • 10
  • 27

3 Answers3

1

Just concatenate. var formStr = "<h5>How many " + objectType + "?:</h5>" and so on.

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
1

This is simple. Using your example:

var objectType='book';
var formStr = "<h5>How many " + objectType + "?:</h5><input type='number' id='bookinput' value='' /><input type='button' value='submit' onclick='addbook();' />"
hallleron
  • 1,972
  • 3
  • 13
  • 18
1

--> Replace :

formStr.replace("*objectType*", "books")

--> ES5 concatenation : see other answers

--> ES6 string interpolation :

let formStr = `<h5>How many ${objectType}?:</h5>`
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63