KCD
KCD

Reputation: 1

JQuery driven Dynamic table

I'm trying to create a script where I can:

  1. Add data and append it on the table; and
  2. Edit the data that has been entered.

So far, this is my code:

HTML:

<table class="tbl" style="width: 48%;">
    <tr>
        <td align="center">
            Name</td>
        <td align="center">
            Gender</td>
        <td align="center">
            Contact Number</td>
        <td align="center" width="70px">
            </td>
    </tr>
    <tr>
        <td>
            <input id="txtName" type="text" /></td>
        <td>
            <select id="cmbGender" name="gender">
                <option value="Male">Male</option>
                <option value="Female">Female</option>
            </select></td>
        <td>
            <input id="txtContact" type="text" /></td>
        <td align="middle">
            </td>
    </tr>
    </table>
<button id="btn1">Add</button>

then here's my Javascript:

 $(document).ready(function() {
var num = 0;

    $("#btn1").click(function() {
            num += 1;
        $(".tbl").append("<tr><td>" + $("#txtName").val() + "</td><td>" + $("#cmbGender").val() + "</td><td>" + $("#txtContact").val() +"</td><td><button id=\"edit"+num+"\">Edit</button></td></tr>");
});

for(var i = 1; i <= num; i++) {
    $("#edit"+i).click(function(){
        alert(".tbl tr:eq("+i+")");
        $(".tbl tr:eq("+i+")").append("<tr><td><input type=\"text\" value=\""+$("tr:eq("+i+") td:eq(0)").val()+"\" /></td><td><select><option>Male</option >Male<option></option></select></td><td><input type=\"text\" value=\""+$("tr:eq("+i+") td:eq(2)")+"\" /></td><td></td></tr>");
    });
}
});

Edit : one more thing. It'll be in a form to be processed and sent to the database.

Upvotes: 0

Views: 158

Answers (1)

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

I'd suggest using one of the several existing javascript libraries that already do this very well. My favorite is the DataTables jQuery plugin paired with the DataTables Data Manager Plugin or the jEditable plugin

Upvotes: 1

Related Questions