jQuery Datatables - retrieving information from other pages - javascript

I have got a problem with getting information from jQuery datatable.
Here is the table:
I would like to get information stored in the table. I have tried to do this by this:
var languages=[];
var people=[];
$("select[name='languageID']").each(function(){
languages.push( $(this).val() );
});
$("input:hidden[name='personID']").each(function(){
people.push( $(this).val() );
});
but it is getting values from current chosen page. If I run this in the situation like on the screenshot, only values from page 2 would be pushed to the arrays. I have tried to check where values from page 1 are stored, but I could not find anything. I also looked for it on jQuery datatables homepage
Could anyone help?
Regards
EDIT:
so I should do something like this:
table.column( 0 ).cache( 'search' ).each( function ( d ) { /*action here*/ } );
?
But what should be in action?
When I debug table.column( 2 ).cache( 'search' ); I have got this:
[ choose language ", " choose language ", " choose language ", " choose language ", " choose language ", " choose language " ]
It is first option in "Chosen language" select. I think, that I need something, which would return html code from each cell in column, so that I can analyse it later.

This one turns out harder than expected. At first, I try using the datatable data() API, but that returns the dropdown lists as HTML strings, which are not very useful. Then I come across this article on how datatable deals with form inputs. The trick is to recognize that your datatable object can retrieve nodes from within the document regardless of paging.
A live demo can be found on my jsfiddle.
EDIT: As per discussion with OP, the following codes can be utilized instead of relying on embedded column selectors:
table.$('select[name="languageID"]').each(function(index, value{
languages.push($(value).val());
});

In the legacy api, fnGetData should return what you need.
$(document).ready(function() {
oTable = $('#example').dataTable();
oTable.$('#myButton').click( function () {
var data = oTable.fnGetData( this );
// ... do something with the array / object of data for the row
} );
});
In the new api (v1.10+), you'll probably want column().cache().
http://datatables.net/reference/api/column().cache()

In my case, I should modify my code to:
var languages=[];
var people=[];
table
.column(0)
.nodes()
.each(function(a){
people.push( $(a).find("input:hidden[name='personID']").val() );
});
table
.column(2)
.nodes()
.each(function(a){
languages.push( $(a).find("select[name='languageID']").val() );
});

As #ivan.sim says, it's not so easy to get the full table data, although I finally found a solution which you can use to get values (including hidden inputs etc) from the full table including pages that are not displayed:
table.rows().every(function (rowIdx, tableLoop, rowLoop) {
var data = this.node();
console.log($(data).find('input').prop('checked'));
console.log($(data).find('input[name=someField]').val());
});

Related

Json data from table in an onclick function show in seperate div

I'm trying to get data used in my table to be used in a div when I click on the table. The thing is, there are multiple tables in my script according to the data of my JSON. So my JSON consists of object that consists of object. For example:
My table(s) are rendered like this:
data.forEach(function(somedata){
return '<table><tr><td>'+somedata.something+'</td></tr></table>';
});
Now I've tried to get the onclick to work in this case but I cant seem to figure out how. I'd like to not use specific ID's rendered in the foreach like:
var i=0;
data.forEach(function(somedata){
i++;
return '<table id="'.id.'"><tr><td>'+somedata.something+'</td></tr></table>';
});
the variable somedata consists of an object so I cant just make an onclick in the html code of the table either and send the data in it.
So somedata would look something like this but json encoded:
somedata{
[0]=>array(
'something'=>'test',
'theobject'=>array(...)
),
[1]=>array(etc...)
}
Now what I want is to get the data from theobject in a seperate div as soon as I click on the table that belongs to the right somedata.
I've been thinking of making a jquery on click for this but then I would need specific ID's in the table(if that's the only possible solution then I'd take it). Cant I do something with this or something? Or send the data at the same time it's being rendered cause in my code I can at the moment of course reach to somedata.theobject
I think I'm thinking a bit too difficult about this. Am I?
You can pass this in onclick function like
return '<table onclick=makeObject(this)><tr><td>'+somedata.something+'</td></tr></table>';
And then use the function to get the data
function makeObject(that){
var tbl = $(that).find('tr').map(function() {
return $(this).find('td').map(function() {
return $(this).html();
}).get();
}).get();
}
There are a few ways to go about this. Rather than using the forEach function we can use the jQuery.map function, since you've indicated that you're open to using jQuery :-)
var $els = $.map(data, function(somedata, i){
var $el = $('<table><tr><td>'+somedata.something+'</td></tr></table>')
.click(function(e) {
populateDivWithData(somedata.theobject);
});
return $el;
});
The call to .click inside each will create a separate click handler for each item in data; each click handler then has access to the relevant theobject value.
EDIT: Thanks #Loko for the reminder about the .forEach built-in

Use Datable with Nodejs socket.io

I'm currently starting using Datatables (https://datatables.net) to create tables.
The data in the table are obtained through socket.io from the server.
My problem is when socket.io add data, the table isn't "updated", it says it only have 1 entry and search box is only working on the last element added.
Here is a sample of my code:
socket.on('jobStepsResponse', function(message) {
document.getElementById('listOfJobs').style.display = 'none';
document.getElementById('contentJob').style.display = 'block';
document.getElementById('jobid').innerHTML = "<button onClick=returnToJobList()>Retour</button> Job "+message.idJob;
for(var i=0;i<Object.keys(message.status).length;i++){
document.getElementById('tabstats').innerHTML += '<tr><td>'+Object.keys(message.status)[i]+'</td>'+'<td>'+ts2time(message.status[Object.keys(message.status)[i]])+'</td>'+'</tr>';
}
$(document).ready(function() {$('#example2').DataTable();} );
setInterval( function () { $('#example2').DataTable().ajax.reload( null, false ); }, 1000 );
});
As you can see, I tried using ajax reload but i think its for ajax data sources, so it doesn't work.
As a workaround, i wait for table to be fully populated first, the call the Datatables style which will count all the element added.
Only problem is that it show the unformatted datas for some times so you need to add a DOM control to show a loading thing for example.

Taking Data from Form to collection in Backbone

I am having a very big form which has lot of form columns.
I am putting my form data using this code :
var formData = {};
$("#newwaitlist div").children().each(function(i, el){
formData[el.id] = $(el).val();
});
var waitdriver= new DriverWaitModel(formData);
console.log(JSON.stringify(waitdriver));
this.collection.add(waitdriver);
The data is correctly getting taken.
but i am having a small bug in this.
Inside my form i also have my buttons and also form that takes options(like drop downs).
The above code also logs the button value and its id. Is there a way to remove it before adding to the collection ??
IS the way i am passing my data to the collection correct ?? or is there a better way of doing the same ??
Note
I cannot use backbone-stickit or anyother .. Just with backbone, underscore and jquery we have to do. So ...
You could just do a check for the type, as in el.prop('type'). Like this:
$("#newwaitlist div").children().each(function(i, el) {
if (el.prop('type') !== 'button') {
formData[el.id] = $(el).val();
}
});
The above answer also solved the problem,
But in my case i had also to filter out some form elements that were also of not button type.
So this is how i made it work;
if(el.id!="addDriveBtn"===true){
formData[el.id] = $(el).val();
}
which ever id you dont want to input you can just filter out.
Worked great...
JavaScript and Backbone just rocks

MVC dropdownlist onchange call jquery

I have a SelectList representing a delivery type for an order.
The delivery type reference data has the usual code/description, but also an additional boolean property which indicates if further information needs to be entered for the type selected.
So for Emergency deliveries additional data is required. The additional data entry fields would be set visible if Emergency was selected, otherwise hidden
My ViewModel contains <List>ReferenceDeliveryTypes which contains the 3 properties.
I have created a SelectListItems from the ViewModel data
#Html.DropDownListFor(model => model.DeliveryTypeCode,
new SelectList(Model.ReferenceDeliveryTypes as System.Collections.IEnumerable,
"DeliveryTypeCode", "DeliveryTypeDescription"), new { id = "ddlDeliveryType" })
How can I call a jQuery function on change of the delivery type, pass the selected code and check the Model.ReferenceDeliveryTypes for that code to see if the additional data property is true/false to show/hide the additional fields div?
I have managed to get the jQuery function called to pass the value.
$(function () {
$('#ddlDeliveryType').change(function () {
var value = $(this).val();
alert(value);
});
});
I don't know of any way you can do this using a select list but I suggest the following options:
Simple but a hack - add a string to the end of DeliveryTypeDescription, for example (emergency delivery) and check for that in your change function
Another hack - multiply DeliveryTypeCode by 10 and add 1 on if it's an emergency delivery (and then use mod 10 in your change function)
Use an Ajax lookup function
Load a JavaScript lookup table with the codes which require an emergency delivery
Use a hidden field in your form which contains a string list of the emergency codes with a suitable separator
Good luck
UPDATE
For the hidden field option if you use something like 123|456|789| and then use indexOf having appended a | to the selected ID.
I converted the Model.ReferenceDeliveryTypes to a JSON list which allowed me to access it from the jQuery.
Possibly not the best way, but it allows me to do everything on the client rather than making an AJAX call back. I can now show/hide the inside the if block.
Thought it worth documenting what I did as I've not come across the #Html.Raw(Json.Encode before and it might prove useful for someone who wants to access model data from within jQuery.
Any additional comments welcome.
<script type="text/javascript">
var ReferenceDeliveryTypeJsonList=#Html.Raw(Json.Encode(Model.ReferenceDeliveryTypes))
</script>
#Html.DropDownListFor(model => model.DeliveryTypeCode,
new SelectList(Model.ReferenceDeliveryTypes.ReferenceDeliveryType as System.Collections.IEnumerable,
"DeliveryTypeCode", "DeliveryTypeDescription"), new { id = "ddlDeliveryType" })
$(function () {
$('#ddlDeliveryType').change(function () {
var selectedDT= $(this).val();
$.each(ReferenceDeliveryTypeJsonList, function (index, item) {
if (selectedDT === item.DeliveryTypeCode) {
alert("match " + selectedDT);
}
});
});
});

Inline Table Editing with AJAX

I am trying to use this library that allows for inline table editing, and AJAX updates - well I've been having a ton of trouble figuring out how to communicate between it and my MySQL database that contains all the information contained in the rows.
Here's the code example provided:
Unless you just want people to dink around with the transient-by-nature current page, you'll probably want to define/override the InlineEditor.elementChanged function and do something that saves the user's changes. Here is an example using AJAX to immediately post a change. In this case, I used my handy ajax.js code to do it.
InlineEditor.elementChanged = function( theElement, oldVal, newVal )
{
mySavingIndicator( theElement );
var url = "http://www.myserver.com/update.php?id=" + cell.id + "&val="+newVal;
AJAX.getText( url, function( response ){
clearMySavingIndicator( theElement );
alert( 'Did the save work? ' + response );
}); // end ajax callback function
}; // end elementChanged
What I am really wondering about here is what is cell.id, is it normal Javascript, and what output does it give? How can I use this to allow my cells to be editable and go back to the database? My supervisor really wants inline editing and while I have been working in Javascript and with AJAX all week, it is very difficult for me to provide this to him!
I would think you'd have var url = "http://www.myserver.com/update.php?id=" + theElement + "&val="+newVal; which, may BE the id of the cell being edited.
Or, you may have some existing object 'cell' that, in some 'didStartEditing' type of function, would have the id property set to reflect the element being edited

Categories