JQuery Datatables Add new Row

45,019

Solution 1

$(document).ready(function() {
    $('#example').dataTable();
    $('#addbtn').click(addrow);
} );

function addrow() {
    $('#example').dataTable().fnAddData( [
        $('#fname').val(),
        $('#lname').val(),
        $('#email').val() ] );

}

you need to call the addrow() in the button click.

Add this button in your html code

<input type="button" value="add" id="addbtn" />

Solution 2

Here is the way this is now done in DataTables 1.10

<input type="button" value="add" id="addbtn" />

var dTable = $('#example').DataTable();
$('#addbtn').on( 'click', function () {
    dTable.row.add([
        $('#fname').val(),
        $('#lname').val(),
        $('#email').val() 
    ]).draw();
});
Share:
45,019
Richard
Author by

Richard

Updated on July 09, 2022

Comments

  • Richard
    Richard almost 2 years

    I'm creating a registration page where someone can register up to 20 other people if they wanted to. So I have these text boxes:

    First Name: <br/><input type="text" name="fname" id="fname" /> <br/>
    Last Name: <br/><input type="text" name="lname" id="lname" /> <br/>
    Email: <br/><input type="text" name="email" id="email"/> <br/>
    

    This is my html table with my JQuery intialization of DataTables:

    <div id="tables">
        <table id="table" border="1">
            <thead>
                <tr>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Email</th>
                </tr>
            </thead>
        </table>
    </div>
    
    $('#reg_more').dataTable({
        "bLengthChange": false,
        "bInfo": false
    });
    

    Now I want to put an add button so that the user can input the first and last name, and email and hit add, and it will be put into the table. How do I go about doing this?

  • Richard
    Richard almost 12 years
    ahh much better, i'm brand new to jquery and datatables so it's very hard for me to do this kind of stuff. But this makes much better sense. So I can do this same thing for edit and remove. 1 more thing, how do I post all this data properly so i can add it to a mysql database? Let's say they register themselves and 20 other people, i need to add 21 entries to my mysql database.
  • User 99x
    User 99x almost 12 years
    to register, you can use the jQuery ajax to insert the data into the database.