datatables colReorder order method with array from variable - javascript

I would like to get a dynamically generated array and pass it into the "order" option of colReorder.
The following works fine:
var colOrder = [2,1,0];
$(document).ready(function() {
dataTable = $('#example').DataTable( {
colReorder: true
} );
dataTable.colReorder.order(colOrder);
} );
Note the array colOrder. I can put a variable for that static array into the dataTables order option.
When I test by having javascript alert the contents of colOrder, I get: 2,1,0 (no brackets)
However, the following does not work:
HTML:
<input id="test" type="hidden" value="2,1,0" />
Javascript:
var colOrder = new Array($('#test').val().split(","));
$(document).ready(function() {
dataTable = $('#example').DataTable( {
colReorder: true
} );
dataTable.colReorder.order(colOrder);
} );
When I test by having javascript alert the contents of colOrder this time, I get: 2,1,0 (no brackets) -- I see no difference! The DataTable is generated, and colReorder even works, but the order I provide with that variable doesn't work.
I get the following error: ColReorder - array reorder does not match known number of columns. Skipping.
Can someone help me? Here is the jsfiddle: https://jsfiddle.net/runnerjoe/k47puxux/1/

Your non-functioning code is producting [["2","1","0"]], not [2,1,0]. Remove the new Array wrapper, as it is nesting the values in another array. You may also need to convert the strings to integers:
var colOrder = $('#test').val().split(",").map(function(index) {
return parseInt(index, 10);
});
Updated fiddle

Related

How add new values in drop-down list using plugin "selectory" jquery

I need some help. How can I add new values in code to the list if I use a plugin from jquery. I wrote this code, but the list is empty, although the values are passed to the view. This is probably due to the fact that I am referring to the id of the div tag, but the plugin did not work differently. Help please
<html>
<main>
<form action="#">
<div class="form-group col-xs-12 col-sm-4" id="example-2"> </div>
</form>
</main>
<script>
$('#example-2').selectivity({
items: ['Amsterdam', 'Antwerp'],
multiple: true,
placeholder: 'Type to search a city'
});
function addOption() {
var ul = document.getElementById("#example-2");
for (var item in #ViewBag.List)
{
var value = item;
}
var newOption = new Option(value, value);
ul.options[ul.options.length] = newOption;
}
</script>
</html>
result of code from answer 1
The documentation of the selectivity library covers how to add new options to the dropdown.
The main issue you have is that the output from #ViewBag.List won't be in a format that JS can understand. I would suggest formatting it as JSON before outputting it to the page, then the JS can access this as a standard object, though which you can loop.
// initialisation
$('#example-2').selectivity({
items: ['Amsterdam', 'Antwerp'],
multiple: true,
placeholder: 'Type to search a city'
});
// add options, somewhere else in your codebase...
const $list = $('#example-2')
const options = #Html.Raw(Json.Encode(ViewBag.List));
options.forEach((option, i) => {
$list.selectivity('add', { id: i, text: option })
});
Note that for this to work the JS code which reads from the ViewBag needs to be placed somewhere the C# code will be executed, ie. in a .cshtml file, not in a .js file.

Getting search bar to simultaneously work with another search bar [duplicate]

I'm using DataTables (datatables.net) and I would like my search box to be outside of the table (for example in my header div).
Is this possible ?
You can use the DataTables api to filter the table. So all you need is your own input field with a keyup event that triggers the filter function to DataTables. With css or jquery you can hide/remove the existing search input field. Or maybe DataTables has a setting to remove/not-include it.
Checkout the Datatables API documentation on this.
Example:
HTML
<input type="text" id="myInputTextField">
JS
oTable = $('#myTable').DataTable(); //pay attention to capital D, which is mandatory to retrieve "api" datatables' object, as #Lionel said
$('#myInputTextField').keyup(function(){
oTable.search($(this).val()).draw() ;
})
As per #lvkz comment :
if you are using datatable with uppercase d .DataTable() ( this will return a Datatable API object ) use this :
oTable.search($(this).val()).draw() ;
which is #netbrain answer.
if you are using datatable with lowercase d .dataTable() ( this will return a jquery object ) use this :
oTable.fnFilter($(this).val());
You can use the sDom option for this.
Default with search input in its own div:
sDom: '<"search-box"r>lftip'
If you use jQuery UI (bjQueryUI set to true):
sDom: '<"search-box"r><"H"lf>t<"F"ip>'
The above will put the search/filtering input element into it's own div with a class named search-box that is outside of the actual table.
Even though it uses its special shorthand syntax it can actually take any HTML you throw at it.
For recent and new version of DataTables, You should follow these steps:
1- searching option must be true.
2- Hide default search input:
.dataTables_filter {
display: none;
}
3- Add new search input:
<input type="text" id="search">
4- Request search:
$('#search').keyup(function() {
var table = $('.table-meetups').DataTable();
table.search($(this).val()).draw();
});
This one helped me for DataTables Version 1.10.4, because its new API
var oTable = $('#myTable').DataTable();
$('#myInputTextField').keyup(function(){
oTable.search( $(this).val() ).draw();
})
I had the same problem.
I tried all alternatives posted, but no work, I used a way that is not right but it worked perfectly.
Example search input
<input id="searchInput" type="text">
the jquery code
$('#listingData').dataTable({
responsive: true,
"bFilter": true // show search input
});
$("#listingData_filter").addClass("hidden"); // hidden search input
$("#searchInput").on("input", function (e) {
e.preventDefault();
$('#listingData').DataTable().search($(this).val()).draw();
});
More recent versions have a different syntax:
var table = $('#example').DataTable();
// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
table.search(this.value).draw();
});
Note that this example uses the variable table assigned when datatables is first initialised. If you don't have this variable available, simply use:
var table = $('#example').dataTable().api();
// #myInput is a <input type="text"> element
$('#myInput').on('keyup change', function () {
table.search(this.value).draw();
});
Since: DataTables 1.10
– Source: https://datatables.net/reference/api/search()
I want to add one more thing to the #netbrain's answer relevant in case you use server-side processing (see serverSide option).
Query throttling performed by default by datatables (see searchDelay option) does not apply to the .search() API call. You can get it back by using $.fn.dataTable.util.throttle() in the following way:
var table = $('#myTable').DataTable();
var search = $.fn.dataTable.util.throttle(
function(val) {
table.search(val).draw();
},
400 // Search delay in ms
);
$('#mySearchBox').keyup(function() {
search(this.value);
});
This should be work for you:(DataTables 1.10.7)
oTable = $('#myTable').dataTable();
$('#myInputTextField').on('keyup change', function(){
oTable.api().search($(this).val()).draw();
})
or
oTable = $('#myTable').DataTable();
$('#myInputTextField').on('keyup change', function(){
oTable.search($(this).val()).draw();
})
You could move the div when the table is drawn using the fnDrawCallback function.
$("#myTable").dataTable({
"fnDrawCallback": function (oSettings) {
$(".dataTables_filter").each(function () {
$(this).appendTo($(this).parent().siblings(".panel-body"));
});
}
});
$('#example').DataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "../admin/ajax/loadtransajax.php",
"fnServerParams": function (aoData) {
// Initialize your variables here
// I have assign the textbox value for "text_min_val"
var min_val = $("#min").val(); //push to the aoData
aoData.push({name: "text_min_val", value:min_val});
},
"fnCreatedRow": function (nRow, aData, iDataIndex) {
$(nRow).attr('id', 'tr_' + aData[0]);
$(nRow).attr('name', 'tr_' + aData[0]);
$(nRow).attr('min', 'tr_' + aData[0]);
$(nRow).attr('max', 'tr_' + aData[0]);
}
});
In loadtransajax.php you may receive the get value:
if ($_GET['text_min_val']){
$sWhere = "WHERE (";
$sWhere .= " t_group_no LIKE '%" . mysql_real_escape_string($_GET['text_min_val']) . "%' ";
$sWhere .= ')';
}
If you are using JQuery dataTable so you need to just add "bFilter":true. This will display default search box outside table and its works dynamically..as per expected
$("#archivedAssignments").dataTable({
"sPaginationType": "full_numbers",
"bFilter":true,
"sPageFirst": false,
"sPageLast": false,
"oLanguage": {
"oPaginate": {
"sPrevious": "<< previous",
"sNext" : "Next >>",
"sFirst": "<<",
"sLast": ">>"
}
},
"bJQueryUI": false,
"bLengthChange": false,
"bInfo":false,
"bSortable":true
});

HTML data attributes values. How to change?

I have a div, which I can't edit. Is it possible to multiply the values of the data attribute?
Code:
<div class="reviews" data-page-opts="
{
showform:1,
showsupport:0,
postid:241,
perpage:5,
paginate:1,
classes:reviews_in_content, wrapper:1,
morelink:,
on_postid:0,
num:9999,
hidecustom:0,
snippet:0,
hidereviews:0,
hideresponse:0,
ajax:0,
thispage:1
}
">
</div>
Example:
I want to multiply thispage: 1 by 5 or just to replace 1 with 5. Can I do this with JavaScript/jQuery? Thanks in advance.
Use can use jQuery to get value of data first, and then use JSON.parse(), and then modify, after you modify, you can use JSON.stringify();
Here is example code:
var data = $('div.reviews').attr('data-page-opts');
var dataObj = JSON.parse(data);
dataObj.ajax = 1;
data = JSON.stringify(dataObj);
$('div.reviews').attr('data-page-opts', data);

Iterating through rows in DataTables using JavaScript

Essentially the problem is that I am getting duplicate results in my DataTable.
In my application, the user will enter a value and that value will return an array of objects from the database and those records will then populate in the DataTable. Currently the issue that I am having is that all the records that are in the table are all the same.
There should be 100 different records in the DataTable, instead there is 100 of the exact same record. I am not seeing any examples that show how to iterate though an array of objects from a database, in a way that in can be handled by the DataTable.
I should be able to use rows.add() but that does not have anything displaying in the table and the other option I saw was rows().every() which does not have an example similar to what I am doing.
Any references, resources or insight will be very helpful. Thanks!
User Input:
<p> Year: <input id="YearNbrId" type="text" th:field="*{YearNbr}" /> </p>
Button:
<input type="button" value="Locate" id="goToDetails" />
JavaScript Snippet:
$(document).ready(function() {
var table = $('#Orders').DataTable();
$('#goToDetails').on('click', function() {
var YearNbr = $('#YearNbrId').val();
var url = './eData/locate?YearNbr=' + YearNbr;
$.get(url, function(result) {
console.log(result);
for (var i = 0; i < result.length; i++) {
var myOrder = result[i];
table.row.add([
null, // place holder
myOrder.yearNbr,
myOrder.orderNm,
'<input>', // user input
myOrder.model,
new Date(myOrder.Date).toJSON().slice(0, 10),
myOrder.srcCode,
null,
'<input>'
]).draw(false)
.nodes()
.to$();
}
});
});
});
You might want to check out the JQuery .each function. You probably need to do something like: $(result).each(function(i,obj) {//code here}); Where i is the position in the array and obj is the current record in result.

Javascript push Object to cookies using JSON

Hi All on click button I need to add object to array and then write array to cookies.
From the start this array can be not empty so I parse cookie first.
function addToBasket(){
var basket = $.parseJSON($.cookie("basket"))
if (basket.length==0||!basket){
var basket=[];
basket.push(
{ 'number' : this.getAttribute('number'),
'type' : this.getAttribute('product') }
);
}
else{
basket.push(
{ 'number' : this.getAttribute('number'),
'type' : this.getAttribute('product') }
);
}
$.cookie("basket", JSON.stringify(basket));
}
And HTML
<button type="button" class="btn btn-success btn-lg" number="12" product="accs" onclick="addToBasket()">Add</button>
Unfortunately I'm getting Uncaught ReferenceError: addToBasket is not defined onclick.
Can't understand what am I doing wrong?
Thanks!
I simplified your code a good deal, heres a fiddle: http://jsfiddle.net/yJ6gp/
I wired the click event using jQuery and simplified some of your code (see comments). Note I changed your html a little so I could select the add basket button by class - change as desired.
$(function () {//doc ready
$.cookie.json = true; //Turn on automatic storage of JSON objects passed as the cookie value. Assumes JSON.stringify and JSON.parse:
$('.add-basket').click(function() {
var basket = $.cookie("basket") || []; //if not defined use an empty array
var $this = $(this);
basket.push({
'number': $this.attr('number'),
'type': $this.attr('product')
});
console.log(basket);
$.cookie("basket", basket);
});
});

Categories