Skip to content Skip to sidebar Skip to footer

Add Row On Button Click

Trying to add a row of this table when you click the input 'plus'. My Html Copy

http://jsfiddle.net/brentmn/whgy6/

Solution 2:

I think perhaps you've got tied up in trying to do it in few lines of code, and using frameworks... The following will do what you want, and doesn't require any libraries. If you are worried about the bytes transfered, write clear code and minify it with a minifier such as

http://developer.yahoo.com/yui/compressor/

Here's what worked for me, and it's readable to boot :)

<html><head><title>foo</title><scripttype="text/javascript">functioninsertAfter( referenceNode, newNode ) {
    referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}

functioncloneRow(e) {

  // first find our rowvar elem = e;
  while ( elem.tagName != 'TR' ) {
    elem = elem.parentNode;
  }

  var newElem = elem.cloneNode(true);
  insertAfter(elem, newElem);
}
// ]]></script></head><body><tablename="mytable2"width="100px"border="0"cellspacing="0"cellpadding="0"style="padding-top:5px"><trclass="st"name="st"><tdwidth="80px"style="text-align:center; padding-top:3px;"><inputtype="Text"id="newst"name="newst"maxlength="25"style="width:80px; font-family:Tahoma; font-size:11px;"></td><tdwidth="20px"><inputtype="submit"name="plus"id="plus"value="+"style="width:20px; text-align:center;"onclick="cloneRow(this)"></td></tr></table></body></html>

Credit where credit is due, you can see that I used the insert trick from another answer for part of this answer...

.insertAfter or .append to an Element Id with Javascript. it's a script tag so it can't be with $

Note that this relies on passing in "this" in the html. If you attach it with jQuery or something else, you'll need to look at e.target etc.

Post a Comment for "Add Row On Button Click"