5

I am trying to put some html mark-up inside an array for retrieval later. My editor throws a syntax error on the description1 line, I can't figure out why. Any help would be much appreciated. Code below. Thanks A

var modalcontent = {
  description1 : '<div id = "description"><div class = "tbc">  
  <label class = "tbc" for = "tbc">Description</label>
  </div>
  <div class = "tbc">
  <input type = "text" class = "tbc" name = "description" id = "tbc" placeholder =        "Enter description">
  </div>
</div>
<!--end description div-->'
} 
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
Ant
  • 356
  • 2
  • 15

1 Answers1

6

You have an unclosed string literal. JavaScript strings are not multi line by default.

var modalcontent = {
  description1 : '<div id = "description"><div class = "tbc"> '+
  '<label class = "tbc" for = "tbc">Description</label>'+
  '</div>'+
  '<div class = "tbc">'+
  '<input type = "text" class = "tbc" name = "description" id = "tbc" placeholder = "Enter description">'+
  '</div>'+
  '</div>'+
  '<!--end description div-->'
} 

(fiddle)

Alternatively, you can create multi line string by using the \ character, those only work in newer implementations. See this related question or the language specification.

Note: It's usually not the best idea to store HTML in strings, it makes it harder to debug and work with. You can usually use templates. It's not that there are no good use cases, it's just rarely the case.

Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • Thank you. This is dynamic content to be injected into a form as a field depending on the selection by the user. I had initially held these in a separate html file and was calling them with the jQuery load() function. I thought it might be more professional to include the mark-up in JavaScript as I didn't want the user to access the html file where I store all these divs. Is this what you meant by templates? Thanks A – Ant Jun 22 '13 at 11:55
  • You can have script tags with type `text/template` , store the content in those, then read the content by a single DOM call and render it. That way you can keep working on the templates like normally. You might want to consider injecting state into these scripts using something like Mustache if that suits your needs. String literals in code can get really messy really fast. – Benjamin Gruenbaum Jun 22 '13 at 11:57