1

I am using below code to dynamically add a chunk of html to a div using innerHTML property. Here is my html code:

 <body>
   <form>    
     <div id="date_in"><input type="date" name="arrival"/></div>
     <div id="dat_out"><input type="date" name="departure"/></div>
     <div id="submit"><input type="submit" value="Submit"/></div>
   </form>
 </body>

After the closing body tag I am adding the following JavaScript,

<script type"text/javascript">
  var inDate= document.getElementById("date_in");   
  var inCal= document.createElement("div");
  inCal.id="inCal";
  inDate.appendChild(inCal); 
  document.getElementById("inCal").innerHTML= '<div id="calHeading">
                   <span id="left">Left</span>
                   <spanid="yearMonth">curMonth curYear</span>
                   <span id="right">Right</span>
                 </div>
                 <div id="weeKDays">
                   <span>S</span>
                   <span>M</span>
                   <span>T</span>
                   <span>W</span>
                   <span>TH</span>
                   <span>F</span>
                   <span>SA</span>
                 </div>';
  </script>

I the above code, innerhtml mark-up is not being added, I can see that in view source. What could be wrong with this piece of code?

m2j
  • 1,152
  • 5
  • 18
  • 43
Manu
  • 33
  • 5
  • 1
    Look at your JavaScript error console. You have a syntax error. Literal new lines aren't allowed in JavaScript strings. – Quentin Jun 28 '15 at 18:16
  • JavaScript does not allow multiline string, must be '
    ' +'Left' etc
    – Tero Tolonen Jun 28 '15 at 18:16
  • Side note, you don't need `getElementById` there since you already have a reference to the element via your `inCal` variable. –  Jun 28 '15 at 18:21
  • @Tero: Thanks, it worked. I assumed it, as am php programmer. silly mistake. – Manu Jun 28 '15 at 18:23

1 Answers1

0

You had a syntax error in your JavaScript, because the string was on multiple lines. This should work:

<body>
   <form>

     <div id="date_in"><input type="date" name="arrival"/></div>
     <div id="dat_out"><input type="date" name="departure"/></div>
     <div id="submit"><input type="submit" value="Submit"/></div>

  </form>
 </body>

 <script>
 var inDate= document.getElementById("date_in");
 var inCal= document.createElement("div");

  inCal.id="inCal";    
  inDate.appendChild(inCal);

  document.getElementById("inCal").innerHTML = [
 '<div id="calHeading">',
     '<span id="left">Left</span>',
     '<spanid="yearMonth">curMonth curYear</span>',
     '<span id="right">Right</span>',
 '</div>',
 '<div id="weeKDays">',
     '<span>S</span><span>M</span>',
     '<span>T</span><span>W</span>',
     '<span>TH</span><span>F</span>',
     '<span>SA</span>',
 '</div>'].join('\n');

 </script>
Jon Snow
  • 3,682
  • 4
  • 30
  • 51