简体   繁体   中英

Uncaught TypeError: Cannot call method 'appendChild' of undefined in Meteor JS

I tried giving input tag at runtime in meteor JS but not getting executed. Here pasting the code which i have written... And when we create a button how to add events at runtime... and i got error at execution time : Uncaught TypeError: Cannot call method 'appendChild' of undefined ,so Please check the code and suggest me how to do. waiting for response thank u in advance...

HTML Code :

<head>
  <title>TICTACTOE App</title>
</head>

<body>
  {{> main}}

</body>

<template name="main">
     <h1>Welcome to TICTACTOE App</h1>
    <p><b>Layout Number :</b> <input type="text" id="no" ></p>
</template>

JS Code:

var no;
var newButton;
if (Meteor.isClient)
 {
  // Template.hello.greeting = function ()
  // {
    // return "User Name :";
  // };

  Template.main.events
  ({
    'keydown input#no' : function ()
    {
      // template data, if any, is available in 'this'
      if (event.which == 13) 
        { 
        // 13 is the enter key event
          console.log("You pressed  enter key");
        no = document.getElementById('no');
         if(no.value != '')
         {
           UI();
         }
        }
    }
  });
}
function UI()
{
  console.log("*** UI() ***");
  for(var i = 1 ; i <= no ; i++)
  {
      //TODO:: is there any possibility to add buttons to template at runtime?
      var body = document.getElementsByName('main')[0];
      for(var j = 1 ; j <= no ; j++)
      {
         newButton = document.createElement('input');
         newButton.type = 'button';
         newButton.id = 'btn'+i+j; 
             body.appendChild(newButton);  //here tried by creating a button at runtime      
      }
      var newline = document.createElement('br');
      body.appendChild(newline) 
    }

}
if (Meteor.isServer) 
{
  Meteor.startup(function () 
  {
    // code to run on server at startup
  });
}

Note, I'm not at home and can't test it on my dev machine, but my guess is:

var body = document.getElementsByName('main')[0];

Doesn't call any element on your html, it is the name of your Meteor template.
You need to add an element with the name="main" , eg

<template name="main">
     <h1>Welcome to TICTACTOE App</h1>
     <p><b>Layout Number :</b> <input type="text" id="no" ></p>
     <p name="main"></p>
</template>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM