Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a JavaScript function within an HTML body

I have a JavaScript function that fills a table:

<script>  var col1 = ["Full time student checking (Age 22 and under) ", "Customers over age 65", "Below  $500.00"]; var col2 = ["None", "None", "$8.00"];  function createtable() {     <!--To fill the table with javascript-->     for (var j = 0; j < col1.length; j++) {         if (j % 2 == 0) {             document.write("<tr><td>" + col1[j] + " </td>");             document.write("<td>" + col2[j] + "</td></tr>");         } else {             document.write("<tr  bgcolor='#aeb2bf'><td>" + col1[j] + " </td>");             document.write("<td>" + col2[j] + "</td></tr1>");         }     } } </script> 

I want to execute it within the HTML body. I have tried the following, but it doesn't create the table.

<table>     <tr>         <th>Balance</th>         <th>Fee</th>             </tr>       createtable(); </table> 

How I can execute this function within the HTML body?

like image 590
user2804038 Avatar asked Nov 08 '13 22:11

user2804038


People also ask

How do you call a function inside a div tag?

You can name each function according to the div 's id and call it dynamically using the object["methodName"]() syntax to call it.

Can JavaScript go in body?

JavaScript in body or head: Scripts can be placed inside the body or the head section of an HTML page or inside both head and body. JavaScript in head: A JavaScript function is placed inside the head section of an HTML page and the function is invoked when a button is clicked.


2 Answers

Try wrapping the createtable(); statement in a <script> tag:

<table>         <tr>             <th>Balance</th>             <th>Fee</th>          </tr>         <script>createtable();</script> </table> 

I would avoid using document.write() and use the DOM if I were you though.

like image 130
HaukurHaf Avatar answered Sep 21 '22 01:09

HaukurHaf


First include the file in head tag of html , then call the function in script tags under body tags e.g.

Js file function to be called

function tryMe(arg) {     document.write(arg); } 

HTML FILE

<!DOCTYPE html> <html> <head>     <script type="text/javascript" src='object.js'> </script>     <title>abc</title><meta charset="utf-8"/> </head> <body>     <script>     tryMe('This is me vishal bhasin signing in');     </script> </body> </html> 

finish

like image 42
vishal Avatar answered Sep 23 '22 01:09

vishal