Dharmesh Hariyani
Dharmesh Hariyani

Reputation: 394

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+')'); 
}

Upvotes: 2

Views: 830

Answers (5)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

Working fiddle.

  1. The id attribute should be unique so you could replace the duplicate ones by class attributen example :

    <select class="_cid" name="_cid[0]" >
    <input type="text" value="1" class="_qty" name="_qty[0]"/>
    
  2. Better if you could avoid the inline-event onclick() and the overriding of parameters in every clone and define a general event one time and it will work for all the element, example :

    $('body').on('change','._cid', function(){
        //You code here
    })
    
  3. You don't need to increment the names you have just to leave the array signs empty [] and it will be incremented automatically, example :

    <select class="_cid" name="_cid[]" >
    <input type="text" value="1" class="_qty" name="_qty[]"/>
    

Hope this helps.


$(function(){

  $('body').on('change','._cid', function(){
    var id_number = $(this).parents('tr').attr('id').split('_')[1];
    changeCustomCategory($(this).val(),id_number);
  })

  $('body').on('change','._qty', function(){
    var id_number = $(this).parents('tr').attr('id').split('_')[1];
    _doVariation(id_number);
  })

})

function addRow()
{
  var new_id = $('.row').length + 1;

  var new_row = $("#testTable tr:first").clone().attr('id','row_'+new_id);

  $("#testTable").append(new_row);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="testTable">
  <tr id="row_1" class="row">
    <td>
      <select class="_cid" name="_cid[]" >
        <option value="">--Select Product--</option>
        <option value="test">Test</option>
      </select>

      <input type="text" value="1" class="_qty" name="_qty[]"/>
      <input type="text" class="textfield" value="0.00" class="item1_total" name="item1_total" readonly>
    </td>
  </tr>
</table>

<input type="button" onclick="addRow()" value="Add Row">

Upvotes: 0

Hozeis
Hozeis

Reputation: 1742

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+')');
}

Upvotes: 0

Dharmesh Hariyani
Dharmesh Hariyani

Reputation: 394

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

    var total_row = $("#total_row").val();
    var _previousId = parseInt(total_row);
    var new_id = parseInt(total_row) + 1;
    $("#total_row").val(new_id);
    var currentRow = $("#testTable tr:first").clone();
    $("#testTable").append(currentRow);
    $(currentRow).find('#_cid').attr("name","_cid["+new_id+"]");
    $(currentRow).find('#_qty').attr("name","_qty["+new_id+"]");
    $(currentRow).attr("id","row_"+new_id);
    $(currentRow).find('#_cid').attr('onclick',"changeCustomCategory(this.value,'"+new_id+"')");
    $(currentRow).find('#_qty').attr('onclick','_doVariation('+new_id+')');}

Upvotes: 0

Ismail RBOUH
Ismail RBOUH

Reputation: 10470

You can perform your changes as the following:

//....

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

//Change1
newRow.attr('name', '_cid['+new_id+']');

//Change2:
newRow.find('select').removeAttr('onchange').change(function() {
    changeCustomCategory(this.value, new_id);
});

//Change3:        
newRow.find('input:first').removeAttr('onchange').change(function() {
    _doVariation(new_id);
});

//....

Demo: https://jsfiddle.net/4c0v2d50/

Upvotes: 1

Taplar
Taplar

Reputation: 24965

Removed the inline binding and bound to the element in the logic. Started changing the first thing you were trying to do with a regex. You can see how you like this approach.

jQuery(function($) {
    //cache selectors
	var $total_row = $("#total_row"),
		$table = $("#testTable");
	
	$(".addRow").on('click', function addRow() {
        var total_row = $total_row.val(),
			_previousId = parseInt(total_row),
			new_id = _previousId + 1;
		
		$total_row.val(new_id);
		
		var $new_row = $table.find("tr").eq(0).clone();
		
		$new_row.attr("id", "row_"+ new_id);
		$new_row.find("select").attr("name", "_cid["+ (new_id - 1) +"]");
		
		$table.append($new_row);
		


//        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 + ')');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<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" value="Add Row" class="addRow">

Upvotes: 0

Related Questions