How to modify values that are result of fnGetNodes() function - javascript

I'm trying to get all of the values on a 4th column of my datatable table. (both visible and unvisible rows).The 4th column of each row is consist of a checkbox. After I get them, I need to change 'checked' property of them and send back to table. Currently, I'm able to get data but I do not know how could I send them back to datatable after modifying. In the column that I'm trying to retrieve checkboxes are exist. Here is my code :
$(document).on('click', '#select_all', function()
{
var rows = $("#results_container table").dataTable().fnGetNodes();
var cells = [];
for(var i=0;i<rows.length;i++)
{
// Get HTML of 4rd column (for example)
console.log( $(rows[i]).find("td:eq(3)"));
}
});
Here is what console.log statement prints out :
[td.sorting_1, prevObject: jQuery.fn.jQuery.init[1], context: tr, selector: "td:eq(3)"]
The check property that I want to modify is under 0: td.sorting_1 -> childNodes screen shoot of my console view
So how could I changed this checked value and see the result on my datatable?

In your for loop store your data to a variable:
var dataHolder = $(rows[i]).find("td:eq(3)")
Then access your data like this:
dataHolder = dataHolder[0].childNodes;
Then try your console.log() on the dataHolder.
You should be able to change the value like this:
dataHolder[1].checked = true;

Related

tabulator update column data

I've a table set up with Tabulator with unknown data ( pulled from a file) so i can't make a column definitions setup for it except for general setup that works with any kind of data.
now I'm in situation that i need to add certain code for each row under column code which is included with the existing table.
i looked for away to add code something like SX0001 on the first row and just add 1 each row so the second row would be look like SX0002
I've checked this link http://tabulator.info/docs/4.1/update#alter-replace i saw some functions that works on rows but not columns .
solution i'm trying to achieve:-
the link includes under updateData function that i need to have index with default value (Id)
giving that I'm not sure what type of date it might have or be included with the table i've added a new column using this code
table.addColumn({title:"id", field: "id" , formatter:"rownum",width:40, align:"center"} , true)
now I don't know how to get the Length of the Column to loop through each one of the column and run function like this
var no = 1000;
var str = "SX";
var x = str + no ;
table.updateData([{id:1, code:x}]);
var no = no +1;
is there's anyway to do this ?
You can retrieve the data stored in the table using the getData function.
var data = table.getData();
This will return an array containing the data objects for each row in the table.
Then to get your lenght just do data.length
If you want to count the table data the getDataCount exactly for this, which returns a count of rows in the table:
var count = table.getDataCount();
But actually your current approach will result in the table being redrawn a load of times as you update the row data.
Mutators
Instead you should look at using a Mutator, these allow you to alter data as it enters the table, so in this case you could do something like this:
//global variable to keep track of row id
var rowCount = 0;
//custom mutator
var idMutator = function(value, data, type, params, component){
//increment rowCount and assign as column value
return rowCount++;
}
//in your column definition set this mutator
{title:"ID", field:"id", mutatorData:idMutator}
By using this approach the value is set as the data is loaded into the table, nothing needs to be redrawn and the whole proceess is much more efficient

Get the list of tr elements having the same data answer id

I have the following data where I want to remove the row and it's associated child rows.
This is displayed in screen-shot
With the following I am trying to delete all child rows whose data-answer-id is equal to the data-question-id of the tr because that is what defined as parent/child records.
I am trying something like this:
var table = $("table#sortable tbody");
var childrens = $(this).closest('tr').attr('data-question-id');
var childrens = $(thisRow).hasClass('parent').attr('data-question-id');
table.find('tr.childrow').each(function (key) {
<!--- missing this piece here need to create a comma separated list -->
});
From your question it's not quite clear about whether you want to delete all rows with "data-answer-id" attribute or just specific row which have specific "data-answer-id" value.
I'm assuming that below code returns the value of particular "data-question-id" which you want to delete.
$(this).closest('tr').attr('data-question-id')
So as per your snapshot this should return 130. Then you can delete all which have data-answer-id=130 by following attribute selector.
$('[data-answer-id=130]').remove();
Your complete code would be like below.
var table = $("table#sortable tbody");
var questionid = $(this).closest('tr').attr('data-question-id');
table.find('tr.childrow[data-answer-id=' + questionid + ']').remove();

Error: Cannot read property 'replaceChild' of undefined

I am trying to update a table to display the new row when I save a record. My code currently loads the entire table again along with the existing table. For example, I'm seeing rows 1-15, then I add a row and see 31 total rows, rows 1-15 and then rows 1-16 all in the same table.
Here is my code for the replace function which calls my original load function when it's time to replace the data. I based this off another example I saw.
function replaceData() {
var old_tbody = document.getElementsByTagName('tbody');
var new_tbody = document.createElement('tbody');
loadData(new_tbody);
old_tbody.parentNode.replaceChild(new_tbody,old_tbody);
console.log("Data replaced");
}
I'm clearly not a JavaScript expert so any help would be appreciated.
getElementsByTagName function returns a HTML Collection (array-like object), that means that you have to specify which item of that array you want (even if there is only one item).
So your code basically should be:
var old_tbody = document.getElementsByTagName('tbody')[0];
Or you can use querySelector which returns only the first matched element. Like this:
var old_tbody = document.querySelector('tbody');
getElementsByTagName actually returns a collection of elements, so parentNode
doesn't work. To get the actual DOM node you would do the following.
var old_tbody = document.getElementsByTagName('tbody')[0];

SharePoint - Use JavaScript to get the list items after filter is applied

Consider I have a list called "test"
And it has 5 list items (say a, b, c, d, e)
Now that I apply filter manually on the list items for a particular field
Now the result is 3 list Items.
Now I want to read the fields of these 3 list items through JavaScript & do calculation on it.
I need to access the fields of the currently displayed (after filter is applied manually)
I do not want to filter it in Javascript. But I want to filter some field manually & then I want to read the displayed result. Can anyone help ?
The following jQuery will get all the values for a column for the rows that are displayed. It works on SharePoint 2010. I left the code very verbose and with debugging statements so it's easier to understand. Keep in mind that this code will not run in IE with the console closed unless you remove the console.log and debugger lines.
$(document).ready(function() {
var columnHeading = "Title";
var anchor = $("a").filter(function() {
return $(this).text() === columnHeading; //find the link that matches the text in the columnHeading variable
});
var th = anchor.closest("th"); //Get the parent table header
var columnIndex = th.index(); //Get the index of the table header in the row for use on other rows
var table = th.closest("table");
var i;
debugger;
table.find("tbody").first().find("tr").not(":first").each(function() { //Loop over every row in the table EXCEPT the first row because its the table header
i = $(this).find("td").eq(columnIndex); //find the td element at the index we determined earlier
console.log($(i).text()); //get the text in the td. You may need to parseInt before any mathematical formulas.
});
});
If you need clarification on anything, please let me know.

how to construct JSON before submitting form using javascript

I have the following demo on jsFiddle. I would like to submit this form using javascript and send a JSON object back to my controller.
As you can see multiple rows can be added to the table and submitted. In my JSON data I would like to keep track of which checkboxes got clicked for which rows. So for example, based on the below screen shot:
I would like the JSON object to look like this:
{light:[{red:on}, {yellow:off},{green:on}], dark:[{red:off}, {yellow:off},{green:on}]}...
The code I came up with looks like this:
var jsonObject = {};
$('.input-row').each(function(index, row) {
var innerObject = {};
$(':checkbox', row).each(function(index, checkbox) {
innerObject[checkbox.name] = checkbox.checked ? 'on' : 'off';
});
var key = $('input[type="text"]', row).val();
jsonObject[key] = innerObject;
});
console.log(jsonObject);
// use jsonObject somehow
We're creating an empty object that will be our overall JSON object (called jsonObject).
Then we're iterating over each of the rows of inputs (I've added an input-row class to these so they can be selected easily).
For each row, we create another empty object (called innerObject), then iterate over its checkboxes. For each checkbox, we add a property to innerObject: the key is the name attribute/property of the checkbox, the value is on or off depending on the checked state. Finally, we get the value of the text input on that row to use as the key in jsonObject, and add the property to it.
Here's a working example of the above code.
The easiest way to serialize a form as JSON is to use jQuery's serializeArray()
JSON.stringify($('form').serializeArray());
You should build your own JSON string and then use jQuery.parseJSON() to do this loop all your tr elements in the table and collect the information you need.
The below code is a start for you according the html in fiddler.
var strJSON = '';
$("#blacklistgrid tr").each(function (i) {
if (i != 0)
{
var currentRow = $(this)
strJSON += "{ " + currentRow.find("input[name='shade']").val() +"[{red: currentRow.find("input[name='red']").is(":checked")} ] }";
}
});
var theJSON = jQuery.parseJSON(strJSON);
please check the correct format for JSON string and I could not check the code if it working but you can get the logic here.

Categories

Resources