0

I am trying to set the onClick property of a dynamically generated div in a loop but the code below is not working beyond generating the divs. Can someone please help me out?

<script type="text/javascript">
function gengrid()
      {
          var i=0;
          var num_stud=8;
          var newdiv;
          var divIdName;
          var maindiv;
          for(i=1;i<=num_stud;i++)
          {
             newdiv = document.createElement('div');
             divIdName = '50'+i;
             newdiv.setAttribute('id',divIdName);
             newdiv.onClick= function(){addit(i);};
             newdiv.innerHTML = '<img src=50'+i+'.jpg alt="a"></img>';
             maindiv=document.getElementById('main');
             maindiv.appendChild(newdiv);
          }
      }
   gengrid();
   function addit(picno)
      {
          alert(picno+'');
       } 
  </script>
3
  • Try newdiv.onclick with simple c. Commented Sep 10, 2013 at 8:12
  • Small case c works , thankyou Commented Sep 10, 2013 at 8:20
  • now it always alerts you 9 , right? Commented Sep 10, 2013 at 8:27

1 Answer 1

1

The onclick method should have a lowercase c.

See this fiddle: http://jsfiddle.net/MTpUV/

<script type="text/javascript">
function gengrid()
      {
          var i=0;
          var num_stud=8;
          var newdiv;
          var divIdName;
          var maindiv;
          for(i=1;i<=num_stud;i++)
          {
             newdiv = document.createElement('div');
             divIdName = '50'+i;
             newdiv.setAttribute('id',divIdName);
             newdiv.onclick= function(){addit(i);};
             newdiv.innerHTML = '<img src=50'+i+'.jpg alt="a"></img>';
             maindiv=document.getElementById('main');
             maindiv.appendChild(newdiv);
          }
      }
   gengrid();
   function addit(picno)
      {
          alert(picno+'');
       } 
  </script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.