Dharmesh Hariyani Dharmesh Hariyani - 5 months ago 12
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">
<td>
<select onchange="changeCustomCategory(this.value,'1');" id="_cid" name="_cid[0]" >
<option value="">--Select Product--</option>
<option value="test">Test</option>
</select>
<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>
</td>
</tr>
</table>

<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

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
id="item1_total" 
class="item1_total"

Javascript

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

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

    $currentRow.attr(id,"row_"+new_id);
    $currentRow.find('select').attr('onclick',"changeCustomCategory(this.value,'"+new_id+"')");
    $currentRow.find('._qty').attr('onchange','_doVariation('+new_id+')');
}