Sandhurst
Sandhurst

Reputation: 1180

Trying to call a function in javascript

This is my code all I need to do is call a function which will write the contents to a dynamic div

<script language='javascript' type='text/javascript'>
function getComments(id)
{
  alert(id);
}
var resultSet="";
function CreateDiv()
{

resultSet+="<br/><div id='"+rows.data[i].id+"'></div><script language='javascript' type='text/javascript'> getComments("+rows.data[i].id+"); <\/script>";
}
window.onload=CreateDiv;
</script>

The function getComments is not being called at all

What's that I am missing here

Upvotes: 0

Views: 129

Answers (3)

Karl Laurentius Roos
Karl Laurentius Roos

Reputation: 4399

Try replacing the createDiv function with this:

function CreateDiv(){
    resultSet += "<br/><div id='"+rows.data[i].id+"'></div>" + getComments(rows.data[i].id);
}

It should work flawlessly.

Upvotes: -1

T.J. Crowder
T.J. Crowder

Reputation: 1073998

There are a few problems there.

  1. You're referencing rows without defining it anywhere, which will cause an exception.
  2. Assuming you define rows somewhere you haven't shown, the code's just creating a string containing a script tag and putting that string in resultSet. To cause the code inside the script tag to run, you'd have to assign resultSet to innerHTML on some element.
  3. There's an extra ) in your call to getComments within the generated script.

Separately: Your id values would appear to be numbers (this is based on your passing them into getComments with no quotes around them). Note that using id values starting with a digit is allowed in HTML5, but not in earlier versions of HTML and not in CSS, so it's probably best avoided.

There's almost certainly a better way to do what you're actually trying to do, you may consider a separate question outlining the goal, how you've approached it so far, and asking for alternatives.

Upvotes: 4

DOK
DOK

Reputation: 32831

I would suggest that you break the code down into steps while you debug it. Specifically where you populate resultSet. Break it down at each plus sign. Then you can step through it and see how it is being populated.

resultSet+="<br/><div id='";
resultSet+=rows.data[i].id;

and so on.

Secondly, have a look in View Source to see what this looks like on the page when you run it. Does the HTML look properly formed?

Also, I am questioning whether that final <\/script> in resultSet is correct.

Upvotes: 0

Related Questions