Dharmesh Hariyani Dharmesh Hariyani - 1 year ago 74
Javascript Question

Table Add More Row using javascript

I am adding dynamic row to table. But when adding new row, i want to replace some string on new row. But it is not working.

<table id="testTable">
<tr id="row_1">
<select onchange="changeCustomCategory(this.value,'1');" id="_cid" name="_cid[0]" >
<option value="">--Select Product--</option>
<option value="test">Test</option>
<input type="text" onchange="_doVariation(1);" value="1" id="_qty" name="_qty[0]"/>
<input type="text" class="textfield" value="0.00" id="item1_total" name="item1_total" readonly>

<input type="hidden" value="1" id="total_row">
<input type="button" onclick="addRow()" value="Add Row">

This is my HTML code.

function addRow(){
var total_row = document.getElementById("total_row").value;
var _previousId = parseInt(total_row);
var new_id = parseInt(total_row) + 1;
document.getElementById("total_row").value = new_id;

var table = document.getElementById("testTable");
jQuery("#"+ table.rows[0].id).clone().appendTo("#testTable");

var totalTableRow = table.rows.length;
var currentRow = table.rows[totalTableRow-1];

currentRow.id = "row_"+new_id;

currentRow.innerHTML = currentRow.innerHTML.replace('_cid\['+ new_id-1 +'\]','_cid['+new_id+']');
currentRow.innerHTML = currentRow.innerHTML.replace(new RegExp("changeCustomCategory(this.value,'"+_previousId+"')","g"),'changeCustomCategory(this.value,'+new_id+')');
currentRow.innerHTML = currentRow.innerHTML.replace('_doVariation('+_previousId+')','_doVariation('+new_id+')');

Answer Source

I would suggest sticking to jquery functions and not mixing too much with plain javascript. It makes it easier to code and follow.

I believe this is what your trying to do:

change HTML

id="_cid" name="_cid[0]"//change in select to
class="_cid" name="_cid[]"//_cid[] will automatically increment

id="_qty" name="_qty[0]"//same in input 
class="_qty" name="_qty[]"

//you should also change


function addRow(){
    var new_id = $("#total_row").val() + 1;

    var $currentRow = $("#testTable tr:first").clone();

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download