Reputation: 11
Can i pass a function to innerHTML ?? I thought of passing a function name data() to the innerHTML. Is it possible ?? I want a button to be created and that button should display a table when clicked.
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML = data();
data()
{
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>
}
}
</script>
</body>
</html>
Upvotes: 0
Views: 2776
Reputation: 700212
You need to call the function, not just evaluate the identifier:
<button onclick="myFunction()">Try it</button>
The function that you use for the content has to contain Javascript, not HTML code. It should return a string that can be used by the innerHTML
property:
data()
{
return '<table>' +
' <tr>' +
' <th>Month</th>' +
' <th>Savings</th>' +
' </tr>' +
' <tr>' +
' <td>January</td>' +
' <td>$100</td>' +
' </tr>' +
'</table>';
}
Upvotes: 0
Reputation: 2014
try this one
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML = data();
}
function data()
{
var html = '<table>';
html += '<tr>';
html += '<th>Month</th>';
html += '<th>Savings</th>';
html += '</tr>';
html += '<tr>';
html += '<td>January</td>';
html += '<td>$100</td>';
html += '</tr>';
html += '</table>';
return html
}
</script>
</body>
</html>
Upvotes: 2