1

I want to add new row when the button is clicked. Below is my code.

<div class="table">
<div id="rows" class="row">

<div id="col1" class="p2">
  <asp:CheckBox id="checkbox1" runat="server" Text="" TextAlign="Right" />
</div>

<div id="col2" class="p3">&nbsp;</div>
<div id="col3" class="p4">
  <asp:TextBox ID="TextBox2" runat="server" Text="2.00"/>
</div>

<div id="col4"class="p5">&nbsp;</div>
<div id="col5" class="p6">
  <asp:TextBox ID="TextBox3" runat="server" Text="1.00"/>
</div>

<div class="row2" style="text-align:center;">
  <button class="clsButton" id="addrow">Add Row</button>
</div>
</div>

below is my jQuery code:

 var cloneCount = 1;

    //add new row
    $("#addrow").click(function () {
        $('#rows')
        .clone(true)
        .attr('id', 'rows' + cloneCount++, 'class', 'row')
       .insertAfter('[id^=rows]:last');
        return false;
    });

The button does not seems to be working. Which part was wrong? I'm really new in JavaScript. Im using VisualStudio 2012, in .aspx form and C# language. Thanks for helping!

3
  • What are you doing with var obj = document.getElementById("checkbox3"); even it's not available in youe snippet. Commented Dec 14, 2016 at 8:32
  • soryy @surya. My bad. I'll fix it now. Commented Dec 14, 2016 at 9:10
  • Hmm, if you are in a need of cloning it, you need to do something like row1 = row.cloneNode(true); and then document.getElementById('table').append(row1); But this will lead you to duplicate the IDs. So use classes instead. Commented Dec 14, 2016 at 9:45

2 Answers 2

1
function AddRow() {
    var row = document.getElementById("row1");
    var row1 = row.cloneNode(true);
    var box = document.getElementById("table");
    box.appendChild(row1);
}

This is the answer you need I think. But it's not the good practice as you'll be duplicating the IDs here. Use class instead of id.

Sign up to request clarification or add additional context in comments.

2 Comments

I'd try but it still didnt work. Do I need to change in the css?
if you are using document.getElementsByClassName. It'll return you an array of the elements having the class and appendChild works on the element, not the class. You can use document.getElementsByClassName("row")[0] for now.
0

I changed from JavaScript to jQuery. And the problem were solved. Thanks for helping. below is my answer.

 <script type="text/javascript">
    var cloneCount = 1;

    //add new row
    $("#addrow").click(function () {
        $('#row')
        .clone(true)
        .attr('id', 'row' + cloneCount++, 'class', 'row')
       .insertAfter('[id^=row]:last');
        return false;
    });
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.