0

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>
1

2 Answers 2

1
<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()" />

jsFiddle example

Sign up to request clarification or add additional context in comments.

2 Comments

@Zee — Yes it is. Not best practice, but certainly valid.
You're right. XHTML 1.0 strict doesn't like onClick, but HTML5 accepts it.
1

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.

1 Comment

That´s good but the live() function is obsolete and replaced by on().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.