junaidkaps
junaidkaps

Reputation: 59

JavaScript onClick() Display

I have an array consisting of several objects containing Strings. I am successfully able to display the array by using:

<td><p onclick="theMiddle(this)">The Middle</td>

As you see from the td tag this is part of a table. Issue is that the browser opens up a new page to display my text. I have been trying to display the array above my table in a p tag.

//JavaScript
var arrayTheMiddle = new Array (showName.theMiddle, beginingTime.theMiddle, 
network.abc, duration.thirty, rating.general, description.theMiddle, showImage.theMiddle);  

function theMiddle(obj){
   for(i=0; i < arrayTheMiddle.length; i++)
     {
      document.write(arrayTheMiddle[i] + "<br>");
     }
}

//HTML File

<p>Would like the array/function displayed here while the user clicks within the table below (entire table has not been listed)</p>

<td><p onclick="theMiddle(this)">The Middle</td>

Unfortunately I am constantly failing at utilizing get element by id to call my function which consists of an array. I have searched for all sorts of stuff, yet frankly I'm lost. Not even sure if my approach is correct at this point. I'm sure this is one of those simple things that are blowing over my head!

Upvotes: 0

Views: 468

Answers (1)

SAJ14SAJ
SAJ14SAJ

Reputation: 1708

Strongly suggest using one of the several excellent JavaScript frameworks to do this type of work. I prefer Dojo, many love jQuery.

There isn't enough context here to see what is not working, but you almost always are better off avoiding document.write, which simply appends text to the HTML of the document--I don't think that is what you want in this case.

You want to create child nodes of some container node. Normally, you would put a container node in your markup with no content for that purpose, lets call it <div id='container'>.

Then you would do something like this (I am far too lazy to test hand-coded DOM manipulation, but this is the idea):

var container = document.getElementById('container');
for (var m : theMiddle) {
   if (theMiddle.hasOwnProperty(m)) {
      var txt = document.createTextNode(m);
      container.appendChild(txt); 
      var br = document.createNode('br'); // I don't approve of br, but that is not relevant here
      container.appendChild(br);
   }
}

Upvotes: 1

Related Questions