表使用javascript添加更多行

时间:2016-06-29 11:37:09

标签: javascript jquery html

我正在向表中添加动态行。但是当添加新行时,我想在新行上替换一些字符串。但它没有用。

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

这是我的HTML代码。

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

5 个答案:

答案 0 :(得分:1)

您可以按以下方式执行更改:

//....

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

//....

演示: https://jsfiddle.net/4c0v2d50/

答案 1 :(得分:0)

我建议坚持使用jquery函数,而不是混合使用普通的javascript。它使编码和跟踪变得更容易。

我相信这是你要做的事情:

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

答案 2 :(得分:0)

删除了内联绑定并绑定到逻辑中的元素。开始改变你试图用正则表达式做的第一件事。你可以看到你喜欢这种方法。

&#13;
&#13;
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 + ')');
    });
});
&#13;
<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">
&#13;
&#13;
&#13;

答案 3 :(得分:0)

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

答案 4 :(得分:0)

<强> Working fiddle

  1. id属性应该是唯一的,因此您可以通过class attributen替换重复的属性示例:

    <select class="_cid" name="_cid[0]" >
    <input type="text" value="1" class="_qty" name="_qty[0]"/>
    
  2. 更好的是,如果你可以避免内联事件onclick()并覆盖每个克隆中的参数并定义一般事件一次,它将适用于所有元素,例如:

    $('body').on('change','._cid', function(){
        //You code here
    })
    
  3. 您不需要增加名称,只需将数组符号保留为空[],它就会自动递增,例如:

    <select class="_cid" name="_cid[]" >
    <input type="text" value="1" class="_qty" name="_qty[]"/>
    
  4. 希望这有帮助。

    &#13;
    &#13;
    $(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);
    }
    &#13;
    <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">
    &#13;
    &#13;
    &#13;