Rectangle 27 4

I decided to insert my own class to the parent row and use the row.add() function to add the child rows manually with some JQuery.

$('.parentrow').closest('tr').each(function(){
        var row = table.row(this);
        childrows = $(this).closest('tr').nextUntil('.parentrow');
        row.child(childrows).show();
    });

Works perfectly. Datatables should do this simple by adding a class to row.

javascript - JQuery Datatables: How to add child row? - Stack Overflow

javascript jquery twitter-bootstrap jquery-datatables
Rectangle 27 4

I know this is quite an old thread, but this might help others. The easiest way I do it to add id attribute to the last added row as soon as I called the data table function fnAddData is:

$('#table').dataTable().fnAddData( ['col1','col2','col3'] );     

$('#table tr:last').attr('id','col'+row_id);

if the size of data you are adding is larger than the number of rows you display in one page. this won't work.

javascript - jQuery DataTables: How do I add a row ID to each dynamica...

javascript jquery datatables
Rectangle 27 27

var addId = $('#mimicTable').dataTable().fnAddData([
  alarmID,
  'col2',
  'col3',
  'col4',
  'col5'
]);

var theNode = $('#mimicTable').dataTable().fnSettings().aoData[addId[0]].nTr;
theNode.setAttribute('id','alarmNum' + alarmID);

addId is defined just above. From the documentation, fnAddData returns an array of integers, representing the list of indexes in aoData that have been added to the table. As we are only adding one row, then it is returning the index added.

javascript - jQuery DataTables: How do I add a row ID to each dynamica...

javascript jquery datatables
Rectangle 27 1

You can use DT_RowId when you add new row, and use object instead an array, see below:

$('#mimicTable').dataTable().fnAddData({
            'DT_RowId': alarmID, 0:'col2', 1:'col3', 2:'col4',
            3:'col5', 4:'col6', 5:'col7'
        });

You should always explain your answers instead of just pasting a block of code

Looked around forever before I saw this snippet which helped me figure out the cryptic error I was getting. Thanks for this!

javascript - jQuery DataTables: How do I add a row ID to each dynamica...

javascript jquery datatables
Rectangle 27 2

var newRow = oTable.fnAddData( [ etc..]);
var oSettings = oTable.fnSettings(); 
var nTr = oSettings.aoData[ newRow[0] ].nTr;
nTr.id = 'new id';

javascript - jQuery DataTables: How do I add a row ID to each dynamica...

javascript jquery datatables
Rectangle 27 1

There is something unexpected with your code in the jsbin, even if it appears to be working. It initializes with the "browsers" data set. Then it clears. Then it makes a new table with one row. Then it clears. Then it makes a new table with two rows. Then it clears. Then it makes a new table with three rows.

I'd have to get a better sense of the code sample and its end goal (and alas my attention is diverted elsewhere right now) but you should be aware that fnRowCallback SHOULD be the way to do this, and that there are many redundant table constructions and row additions that are going to impact performance as well as flexibility with modifying rendering in the future.

Have you folded the updated code into the jsbin? I'd be curious to poke around, too. I could help you find any anomalies.

javascript - jQuery DataTables: How do I add a row ID to each dynamica...

javascript jquery datatables
Rectangle 27 6

Datatables has been updated somehow and it's very straight forward now for adding children rows to parent rows: http://datatables.net/reference/api/row().child()

One of the thing not really obvious, is in case you want to use the same layouts for your children rows like for the parent rows, you need to use the jquery selector, for passing a node instead of a string (written in the documentation but I missed it the first time).

.child(
    $(
        '<tr>'+
            '<td>'+rowIdx+'.1</td>'+
            '<td>'+rowIdx+'.2</td>'+
            '<td>'+rowIdx+'.3</td>'+
            '<td>'+rowIdx+'.4</td>'
        '</tr>'
    )
)

But doing that is wrong: (it will insert your "tr" into a "td" with a colspan of the size of your table and it will obviously break the columns alignment)

.child(
    '<tr>'+
        '<td>'+rowIdx+'.1</td>'+
        '<td>'+rowIdx+'.2</td>'+
        '<td>'+rowIdx+'.3</td>'+
        '<td>'+rowIdx+'.4</td>'
    '</tr>'
)

You saved a life today. Thank you very much

javascript - jQuery dataTables add multiple collapsible rows using the...

javascript jquery datatable datatables
Rectangle 27 7

In order for jQuery DataTables to search child rows you need to add data displayed in the child rows to the main table as hidden columns.

For example, you can add hidden column for extn data property using columns.visible option as shown below:

"columns": [
        {
            "class":          'details-control',
            "orderable":      false,
            "data":           null,
            "defaultContent": ''
        },
        { "data": "name" },
        { "data": "position" },
        { "data": "office" },
        { "data": "salary" },
        { "data": "extn", "visible": false }            
    ],
<thead>
    <tr>
        <th></th>
        <th>Name</th>
        <th>Position</th>
        <th>Office</th>
        <th>Salary</th>
        <th>Extn.</th>
    </tr>
</thead>

See this jsFiddle for code and demonstration. Search for 5407 and the first row will be shown even though data appears only in child row.

this is a far better solution from what i've seen out there and does not require any additional code. clean and simple. thanks for sharing!

this is really useful, but how can I do to show the child row as well as the parent, when the searched data appears only in the child? If the searched data appears only in the parent, the child should remain hidden, and only the parent displayed.

jquery - DataTables search child row content - Stack Overflow

jquery datatables datatables-1.10
Rectangle 27 7

In order for jQuery DataTables to search child rows you need to add data displayed in the child rows to the main table as hidden columns.

For example, you can add hidden column for extn data property using columns.visible option as shown below:

"columns": [
        {
            "class":          'details-control',
            "orderable":      false,
            "data":           null,
            "defaultContent": ''
        },
        { "data": "name" },
        { "data": "position" },
        { "data": "office" },
        { "data": "salary" },
        { "data": "extn", "visible": false }            
    ],
<thead>
    <tr>
        <th></th>
        <th>Name</th>
        <th>Position</th>
        <th>Office</th>
        <th>Salary</th>
        <th>Extn.</th>
    </tr>
</thead>

See this jsFiddle for code and demonstration. Search for 5407 and the first row will be shown even though data appears only in child row.

this is a far better solution from what i've seen out there and does not require any additional code. clean and simple. thanks for sharing!

this is really useful, but how can I do to show the child row as well as the parent, when the searched data appears only in the child? If the searched data appears only in the parent, the child should remain hidden, and only the parent displayed.

jquery - DataTables search child row content - Stack Overflow

jquery datatables datatables-1.10
Rectangle 27 6

Here you have an example assuming the following:

  • Your data row contains the id on first column
columns
var datatablesOptions = {
    "serverSide": true,
    "ajaxSource": '[yourAjaxUrl]',
    "processing": true,
    "columns": [
        { bVisible = false }, // assume this is the id of the row, so don't show it
        null,
        null,
        null,
        /* EDIT */ {
            mRender: function (data, type, row) {
                return '<a class="table-edit" data-id="' + row[0] + '">EDIT</a>'
            }
        }
        /* DELETE */ {
            mRender: function (data, type, row) {
                return '<a class="table-delete" data-id="' + row[0] + '">DELETE</a>'
            }
        },              
     ]
};
$('#table').dataTable(datatablesOptions);
destination
mRender: function (data, type, row) {
    if (row.destination == "d1") {
        return '<a href="destination1?id=' + row.id + '">EDIT</a>'
    }else (row.destination == "d2"){
        return '<a href="destination2?id=' + row.id + '">EDIT</a>'
    } else {
        // some error telling that destination value is unexpected
    }
}

would you mind showing me the mrender in conjunction with my jsfiddle code? I'm just reading the reference you included about columns... but it's just not clear to me yet how to use your example. Also how do I change the hyperlink target based on the value of row[0].destination ? sorry for the many questions.

thanks. But row[0] is returning a value of undefined. and I need a conditional statement... I tried to explain in my Edit 1

Could you debug and check what row is? BTW: I made a change on my code to allow the possibility to perform delete / edit operations trough ajax calls. You should create a click callback for table-edit and table-delete.

javascript - jquery dataTables - how to add an edit and delete option ...

javascript jquery html jquery-datatables
Rectangle 27 3

columns: [
    { 'data': 'LastName' },
    { 'data': 'FirstMidName' },
    { 'data': 'EnrollmentDate' },
    {// this is Actions Column 
        mRender: function (data, type, row) {
            var linkEdit = '@Html.ActionLink("Edit", "Edit", new {id= -1 })';
            linkEdit = linkEdit.replace("-1", row.ID);

            var linkDetails = '@Html.ActionLink("Details", "Details", new {id= -1 })';
            linkDetails = linkDetails.replace("-1", row.ID);

            var linkDelete = '@Html.ActionLink("Delete", "Delete", new {id= -1 })';
            linkDelete = linkDelete.replace("-1", row.ID);

            return linkDetails + " | " + linkEdit + " | " + linkDelete;
        }
    }
{ID: 1, LastName: "Alexander", FirstMidName: "Carson", EnrollmentDate: "/Date(1126386000000)/",}

Note thate I'm using ASP.Net MVC so Html.ActionLink just returning a Link

and the results are

javascript - jquery dataTables - how to add an edit and delete option ...

javascript jquery html jquery-datatables
Rectangle 27 14

Datatables does not support this kind of grouping out of the box. But, as in many cases, there is a plugin available.

It is called RowsGroup and is located here: Datatables Forums. A live example is also included.

If you change the JS part in this example to the below you will have your desired output presented to you in the output window.

$(document).ready( function () {
  var data = [
    ['1', 'David', 'Maths', '80'],
    ['1', 'David', 'Physics', '90'],
    ['1', 'David', 'Computers', '70'],
    ['2', 'Alex', 'Maths', '80'],
    ['2', 'Alex', 'Physics', '70'],
    ['2', 'Alex', 'Computers', '90'],
  ];
  var table = $('#example').DataTable({
    columns: [
        {
            name: 'first',
            title: 'ID',
        },
        {
            name: 'second',
            title: 'Name',
        },
        {
            title: 'Subject',
        }, 
        {
            title: 'Marks',
        },
    ],
    data: data,
    rowsGroup: [
      'first:name',
      'second:name'
    ],
    pageLength: '20',
    });
} );

Here is a screenshot of the result:

I have used this. The rowspan works but the pagination breaks. Any idea of how to get this fixed?

javascript - How to add Rowspan in JQuery datatables - Stack Overflow

javascript jquery datatables html-table
Rectangle 27 5

You can insert placeholder elements via mRender or sDefaultContent and add the actual content and events during the fnRowCallback events. Something like this:

table.dataTable({
    "aoColumns": [{
        "sDefaultContent": '<div class="stuff"></div>'
        "sWidth": "350px"
    }],
    "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
        var element = $(nRow).find("div.stuff");
        // do stuff
        element.on("click",function() {
            alert("do something on row: " + iDisplayIndex);
        });
    }
});

javascript - jQuery DataTables - add jquery generated element with eve...

javascript jquery datatables jquery-datatables
Rectangle 27 1

$('#id tbody').on('click', function(){
    table
        .row($(this).parents('tr'))
        .remove()
        .draw();
});

thanks. I think removing the row from the table on the gui is "easy" but I need to know how to call my back end stuff ... and how to create the options to edit / delete in the first place.

Oh I see what you mean. I've actually only used jQuery DataTables to show data so far. Now's the chance to look into this further.

javascript - jquery dataTables - how to add an edit and delete option ...

javascript jquery html jquery-datatables
Rectangle 27 6

The problem is not that you are trying to add a new row. The error appears already when you try to insert an array of objects as aaData. You must define which property of each object that correspond to a column through aoColumns :

var dataTable = $('#example').dataTable({
    aaData : arr,
    aoColumns: [
        {mDataProp: 'name'},
        {mDataProp: 'company'},
        {mDataProp: 'salary'}
    ]
});

Now the mapping from object to aaData is OK. Note that if you use datatables 1.9.4 or above, mDataProp is renamed to mData (even though it will still work). Next,

$('#table1').dataTable.fnAddData([
  "&nbsp;", "&nbsp;", "&nbsp;"
]);

Is wrong. How should dataTables know how it should handle that array? It raises a huge error in your console (which you probably have not seen, because the script halted already at aaData : arr. The correct way is to call fnAddData on your dataTable-object, and insert data in the same manner as you prior in aoColumns have defined data should be inserted :

dataTable.fnAddData([
  'a', 'b', 'c'
]);
dataTable.fnAddData(
  { name : "a", company : "b", salary : "c" }
);

Is correct. See the examples above and your code working in this fiddle -> http://jsfiddle.net/krs6f/

javascript - Error while adding a new row to DataTable in jQuery - Sta...

javascript jquery datatables jquery-datatables
Rectangle 27 52

I'm pretty late for this but I was looking for an ajax based image uploading solution and the answer I was looking for was kinda scattered throughout this post. The solution I settled on involved the FormData object. I assembled a basic form of the code I put together. You can see it demonstrates how to add a custom field to the form with fd.append() as well as how to handle response data when the ajax request is done.

<!DOCTYPE html>
<html>
<head>
    <title>Image Upload Form</title>
    <script src="//code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript">
        function submitForm() {
            console.log("submit event");
            var fd = new FormData(document.getElementById("fileinfo"));
            fd.append("label", "WEBUPLOAD");
            $.ajax({
              url: "upload.php",
              type: "POST",
              data: fd,
              processData: false,  // tell jQuery not to process the data
              contentType: false   // tell jQuery not to set contentType
            }).done(function( data ) {
                console.log("PHP Output:");
                console.log( data );
            });
            return false;
        }
    </script>
</head>

<body>
    <form method="post" id="fileinfo" name="fileinfo" onsubmit="return submitForm();">
        <label>Select a file:</label><br>
        <input type="file" name="file" required />
        <input type="submit" value="Upload" />
    </form>
    <div id="output"></div>
</body>
</html>

In case you are working with php here's a way to handle the upload that includes making use of both of the custom fields demonstrated in the above html.

<?php
if ($_POST["label"]) {
    $label = $_POST["label"];
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    } else {
        $filename = $label.$_FILES["file"]["name"];
        echo "Upload: " . $_FILES["file"]["name"] . "<br>";
        echo "Type: " . $_FILES["file"]["type"] . "<br>";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

        if (file_exists("uploads/" . $filename)) {
            echo $filename . " already exists. ";
        } else {
            move_uploaded_file($_FILES["file"]["tmp_name"],
            "uploads/" . $filename);
            echo "Stored in: " . "uploads/" . $filename;
        }
    }
} else {
    echo "Invalid file";
}
?>
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https,

@HogRider - if you Google your error message, this is the first result: stackoverflow.com/questions/10752055/ Are you accessing your web pages locally through file://, rather than using a web server? As an aside, it is not best practice to simply copy-and-paste code blindly without first understanding it. I would recommend you go through the code line-by-line to gain an understanding of what is happening before putting the code to use.

@colincameron thank you for clarify a few things i did go through the it line by line and i dont really understand much so i asked the question so that someone might clarify my doubts. I am using local by way xampp to be exact. Can i ask a question that maybe you can clarify?

@Brownman Revival : I know that its too late for the reply.. You got a cross origin error because you opened the html file as file than running it from the server.

javascript - jQuery Ajax File Upload - Stack Overflow

javascript jquery ajax post file-upload
Rectangle 27 51

I'm pretty late for this but I was looking for an ajax based image uploading solution and the answer I was looking for was kinda scattered throughout this post. The solution I settled on involved the FormData object. I assembled a basic form of the code I put together. You can see it demonstrates how to add a custom field to the form with fd.append() as well as how to handle response data when the ajax request is done.

<!DOCTYPE html>
<html>
<head>
    <title>Image Upload Form</title>
    <script src="//code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript">
        function submitForm() {
            console.log("submit event");
            var fd = new FormData(document.getElementById("fileinfo"));
            fd.append("label", "WEBUPLOAD");
            $.ajax({
              url: "upload.php",
              type: "POST",
              data: fd,
              processData: false,  // tell jQuery not to process the data
              contentType: false   // tell jQuery not to set contentType
            }).done(function( data ) {
                console.log("PHP Output:");
                console.log( data );
            });
            return false;
        }
    </script>
</head>

<body>
    <form method="post" id="fileinfo" name="fileinfo" onsubmit="return submitForm();">
        <label>Select a file:</label><br>
        <input type="file" name="file" required />
        <input type="submit" value="Upload" />
    </form>
    <div id="output"></div>
</body>
</html>

In case you are working with php here's a way to handle the upload that includes making use of both of the custom fields demonstrated in the above html.

<?php
if ($_POST["label"]) {
    $label = $_POST["label"];
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    } else {
        $filename = $label.$_FILES["file"]["name"];
        echo "Upload: " . $_FILES["file"]["name"] . "<br>";
        echo "Type: " . $_FILES["file"]["type"] . "<br>";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

        if (file_exists("uploads/" . $filename)) {
            echo $filename . " already exists. ";
        } else {
            move_uploaded_file($_FILES["file"]["tmp_name"],
            "uploads/" . $filename);
            echo "Stored in: " . "uploads/" . $filename;
        }
    }
} else {
    echo "Invalid file";
}
?>
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https,

@HogRider - if you Google your error message, this is the first result: stackoverflow.com/questions/10752055/ Are you accessing your web pages locally through file://, rather than using a web server? As an aside, it is not best practice to simply copy-and-paste code blindly without first understanding it. I would recommend you go through the code line-by-line to gain an understanding of what is happening before putting the code to use.

@colincameron thank you for clarify a few things i did go through the it line by line and i dont really understand much so i asked the question so that someone might clarify my doubts. I am using local by way xampp to be exact. Can i ask a question that maybe you can clarify?

@Brownman Revival : I know that its too late for the reply.. You got a cross origin error because you opened the html file as file than running it from the server.

javascript - jQuery Ajax File Upload - Stack Overflow

javascript jquery ajax post file-upload
Rectangle 27 50

I'm pretty late for this but I was looking for an ajax based image uploading solution and the answer I was looking for was kinda scattered throughout this post. The solution I settled on involved the FormData object. I assembled a basic form of the code I put together. You can see it demonstrates how to add a custom field to the form with fd.append() as well as how to handle response data when the ajax request is done.

<!DOCTYPE html>
<html>
<head>
    <title>Image Upload Form</title>
    <script src="//code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript">
        function submitForm() {
            console.log("submit event");
            var fd = new FormData(document.getElementById("fileinfo"));
            fd.append("label", "WEBUPLOAD");
            $.ajax({
              url: "upload.php",
              type: "POST",
              data: fd,
              processData: false,  // tell jQuery not to process the data
              contentType: false   // tell jQuery not to set contentType
            }).done(function( data ) {
                console.log("PHP Output:");
                console.log( data );
            });
            return false;
        }
    </script>
</head>

<body>
    <form method="post" id="fileinfo" name="fileinfo" onsubmit="return submitForm();">
        <label>Select a file:</label><br>
        <input type="file" name="file" required />
        <input type="submit" value="Upload" />
    </form>
    <div id="output"></div>
</body>
</html>

In case you are working with php here's a way to handle the upload that includes making use of both of the custom fields demonstrated in the above html.

<?php
if ($_POST["label"]) {
    $label = $_POST["label"];
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    } else {
        $filename = $label.$_FILES["file"]["name"];
        echo "Upload: " . $_FILES["file"]["name"] . "<br>";
        echo "Type: " . $_FILES["file"]["type"] . "<br>";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

        if (file_exists("uploads/" . $filename)) {
            echo $filename . " already exists. ";
        } else {
            move_uploaded_file($_FILES["file"]["tmp_name"],
            "uploads/" . $filename);
            echo "Stored in: " . "uploads/" . $filename;
        }
    }
} else {
    echo "Invalid file";
}
?>
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https,

@HogRider - if you Google your error message, this is the first result: stackoverflow.com/questions/10752055/ Are you accessing your web pages locally through file://, rather than using a web server? As an aside, it is not best practice to simply copy-and-paste code blindly without first understanding it. I would recommend you go through the code line-by-line to gain an understanding of what is happening before putting the code to use.

@colincameron thank you for clarify a few things i did go through the it line by line and i dont really understand much so i asked the question so that someone might clarify my doubts. I am using local by way xampp to be exact. Can i ask a question that maybe you can clarify?

@Brownman Revival : I know that its too late for the reply.. You got a cross origin error because you opened the html file as file than running it from the server.

javascript - jQuery Ajax File Upload - Stack Overflow

javascript jquery ajax post file-upload