Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Datatables Add new Row

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?

like image 596
Richard Avatar asked Sep 16 '12 03:09

Richard


People also ask

How to add new row in DataTable in jQuery?

New rows can be added to a DataTable very easily using the row. add() API method. Simply call the API function with the data that is to be used for the new row (be it an array or object). Multiple rows can be added using the rows.

How do you add data to a DataTable?

After you create a DataTable and define its structure using columns and constraints, you can add new rows of data to the table. To add a new row, declare a new variable as type DataRow. A new DataRow object is returned when you call the NewRow method.

How do I add a row to a DataTable in R?

To add row to R Data Frame, append the list or vector representing the row, to the end of the data frame. nrow(df) returns the number of rows in data frame.


2 Answers

$(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" />
like image 115
User 99x Avatar answered Sep 29 '22 08:09

User 99x


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();
});
like image 42
James Sampica Avatar answered Sep 29 '22 08:09

James Sampica