0

I have this written function :

        $(".tdAdd").on("click", function () {
        counter = $('#myTable tr').length - 3; //supposing i only have 2 data
        var count = $("#myTable").length;
        var newRow = $("<tr>");
        var cols = "";
        cols += '<td><input type="button" value="Add" class="tdAdd"/></td>';
        cols += '<td><input type="text" name="name' + counter + '"/></td>';
        cols += '<td><input type="text" name="price' + counter + '"/></td>';

        cols += '<td><input type="button" class="ibtnDel"  value="Delete"></td>';
        newRow.append(cols);
        $("table.order-list").append(newRow); // this is adding row to the end. but i want i on a specific row after where the add button was clicked
        counter++;
    });

    $("table.order-list").on("click", ".ibtnDel", function (event) {
        $(this).closest("tr").remove();
    });




});

and my table is like this :

<table id="myTable" class="order-list">
<thead>
    <tr>
        <td></td>
        <td></td>
        <td>Name</td>
        <td>Price</td>
    </tr>
</thead>
<tbody>
    <tr>
           <td style="text-align: left;">
            <input type="button" id="addrow" value="Add Row" />
        <td>
            <input type="text" name="name" />
        </td>
        <td>
            <input type="text" name="price1" />
        </td>
        <td>
            <input type="button" value="Delete" class="ibtnDel"/>
        </td>
    </tr>
</tbody>        

</table>

Here is a sample Fiddle

I want to add another row below where i clicked the Add row button. the fiddle will only add row on the bottom of the table and only the first button will work. any help would be appreciated. Thanks!

i tried :

$("table.order-list").eq(count-1).after(newRow)

but i still can't get the code to work

1 Answer 1

1

You need to apply the event listener to the document, because the button is dynamically created. EG:

$(document).on("click", '.tdAdd', function () { ... }

See updated fiddle:

http://jsfiddle.net/y8F88/1/

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

7 Comments

Thanks for that!. but how about the insertion of row below where the button was clicked?
See the fiddle, it adds a new row for each one if you change it like i said.
but it adds the row on the bottom. i want it below where it was clicked.
Then use newRow.insertAfter( $(this).closest("tr") ), as in this fork: jsfiddle.net/rplantiko/cDa3N
Have you looked at the forked fiddle? It only adds one row.
|

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.