Reputation: 8225
I have a html form where on button click, JavaScript function needs to start and a new row in a table needs to be inserted. How can I assemble the JavaScript code properly?
Here is the code:
<SCRIPT language="javascript">
function addRow()
{
var table = document.getElementById('table');
var button = document.getElementsByTagName('input')[0];
button.onclick = function() {
var clone = table.rows[table.rows.length - 2].cloneNode(true);
clone.cells[0].firstChild.data =
clone.cells[0].firstChild.data.replace(/(\d+):/,function(str,g1) {
return (+g1 + 1) + ':';
});
table.tBodies[0].appendChild(clone);
};
}
</SCRIPT>
and the html part:
<input type=button value='Change' onclick="addRow" />
<br /><br />
<table cellspacing=0 cellpadding=4 id="table">
<tbody>
<tr><td>Number 1:</td><td><input value=20 style="width:30px" type=text maxlength=2/></td></tr>
<tr><td>Number 2:</td><td><input value=25 style="width:30px" type=text maxlength=2/></td></tr>
<tr><td style="border-top:solid 1px black;border-bottom:solid 1px black;">Sum:</td><td style="border-top:solid 1px black;border-bottom:solid 1px black;"><div>45</div></td></tr>
</tbody>
<tfoot>
<tr><td style="border-top:solid 1px black;border-bottom:solid 1px black;">Sum:</td><td style="border-top:solid 1px black;border-bottom:solid 1px black;"><div>45</div></td></tr>
</tfoot>
</table>
Upvotes: 0
Views: 3112
Reputation: 3538
Javascript uses an event based architecture.
I would recommend investigating jQuery's bind function. If you are dealing with elements which are dynamically added/removed from the page, I would recommend the "on" function instead.
Upvotes: 1
Reputation: 69953
<input type=button value='Change' onclick="addRow" />
addRow
is a function. When you're calling a function like this, you need to add the ()
. Also, you should wrap button
in quotes as it is an attribute value.
Change it to
<input type="button" value="Change" onclick="addRow()" />
Upvotes: 1