Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Doesn't instantiate checkboxes on datatable #167

Open
harsh-r-dave opened this issue Aug 9, 2018 · 6 comments
Open

Doesn't instantiate checkboxes on datatable #167

harsh-r-dave opened this issue Aug 9, 2018 · 6 comments

Comments

@harsh-r-dave
Copy link

Hello,

First of all, it is a great plugin to create switches easily.

I am using it to convert my checkbox to switch. Problem I am facing here is, I have a list of items in the datatable all has a switch element with it to make an ajax call. length of datatable is 10.

var switchElem = Array.prototype.slice.call(document.querySelectorAll('.toggle'));
        switchElem.forEach(function (html) {
            var switchery = new Switchery(html, { color: '#538bc0', secondaryColor: '#B2BABB' });
        });

Using above code, It instantiates first 10 checkbox (first page of datatable) as a switch within datatable plus all other checkbox on the page that are visible on initial load. But it doesn't instantiate any checkbox that are not on first page of datatable. they remain as normal checkbox. So, if I navigate to second or any other page of datatable using datatable pagination, all checkbox are as default HTML checkbox.

I tried instantiating switch on datatable pagination event, but it duplicates the existing switches as well, and it doesn't instantiate switch when I navigate to second page for the first time. I have to open second page, go back to first page and again go to second page to see them as switch. (this is potentially datatable related thing)

Is there a way to instantiate the checkboxes that are not visible on page but are actually on the page?

Due to business constraints, I cannot provide a code.

@AnuroopSuresh
Copy link

Hello,

First of all, it is a great plugin to create switches easily.

I am using it to convert my checkbox to switch. Problem I am facing here is, I have a list of items in the datatable all has a switch element with it to make an ajax call. length of datatable is 10.

var switchElem = Array.prototype.slice.call(document.querySelectorAll('.toggle'));
        switchElem.forEach(function (html) {
            var switchery = new Switchery(html, { color: '#538bc0', secondaryColor: '#B2BABB' });
        });

Using above code, It instantiates first 10 checkbox (first page of datatable) as a switch within datatable plus all other checkbox on the page that are visible on initial load. But it doesn't instantiate any checkbox that are not on first page of datatable. they remain as normal checkbox. So, if I navigate to second or any other page of datatable using datatable pagination, all checkbox are as default HTML checkbox.

I tried instantiating switch on datatable pagination event, but it duplicates the existing switches as well, and it doesn't instantiate switch when I navigate to second page for the first time. I have to open second page, go back to first page and again go to second page to see them as switch. (this is potentially datatable related thing)

Is there a way to instantiate the checkboxes that are not visible on page but are actually on the page?

Due to business constraints, I cannot provide a code.

I'm having the same issue, could not find the solution. This is what i have tried using datatables call back function but with no success,

fnDrawCallback:function (oSettings) {
var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));

            elems.forEach(function(html) {
                var switchery = new Switchery(html);
            });

        }

@harsh-r-dave
Copy link
Author

harsh-r-dave commented Sep 20, 2018

@DawnOfHell
The issue is how the datatables handle the rows. Basically, datatables only draw N rows in the table, and that being said, there will always be only N rows within <table></table> tag. Rest of the rows are not available unless you select the page on datatable. (I don't know how and where datatables save other rows).

Anyway, so I was having same problem with my other project where I have long text of description in last column and I was required to truncate text and add show more link if the text is longer than one line. I do it using JavaScript, so I needed to access content from last column as jQuery object, find specific class from that content, and manipulate it.

Datatable provides a descent way to do that. You need to get the content of particular column as jQuery object and than do your javascripting there.

  1. initialize datatable and get the instance in local variable
    var table = $('#table').DataTable();

  2. use your datatable instance to get the content from table
    var detailsObject = table.column(-1).nodes().to$();
    detailsObject will have jQuery object for column with index of -1. Regardless of page length, it will return values from every row in datatable. (tested for 2 pages, but should work for any number of pages)

  3. iterate through your object to modify them

$(detailsObject).each(function () {
    var content = $(this).find('.show-more').html();
});

Also, you might be interested in datatable's page.dt event. However, it triggers too early, and is not useful for these scenarios.

@harsh-r-dave
Copy link
Author

Below code works for switches on datatable. Approach is the same as I mentioned in my above comment.

// get datatable instance
        var table = $('#table').DataTable();

        // convert column into jquery object
        var dtColumn = table.column(-1).nodes().to$();

        // add your switch selectors into an array from column
        var switchElem = Array.prototype.slice.call(dtColumn.find('.js-switch'));

        // default switchery syntax
        //var switchElem = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));  

        // instantiate switchery on datatable elements
        switchElem.forEach(function (html) {
            var switchery = new Switchery(html, { color: '#0275D8', secondaryColor: '#dee2e6' });
        });

@AnuroopSuresh
Copy link

@harsh18594
Hi, where should i call the above code, i'm populating the datatables using ajax request and server side processing. Below is the sample code i'm working and what i have tried so far.

$("#sampleSwitcheryExampleTable").DataTable({
	"order": [[0, "desc"]],
	sPaginationType: "simple_numbers",
	responsive: true,
	destroy: true,
	//sScrollX: "100%",
	info: true,
	processing: true,
	serverSide: true,
	ajax: {
		type: 'GET',
		url: 'https://datatables.net/examples/server_side/scripts/post.php',
		dataType: 'json',
		dataSrc: function (json) {
			var return_data = [];
			if (json == "") {
			return return_data;
			}
			var editbtn = "", deletebtn = "", profile = "",switchbutton="";
			for (var i = 0; i < json.data.length; i++) {
				
				//here each row is getting a switch button in the last column
				switchbutton = '<input type="checkbox" class="js-switch" checked>';
				
				
				var action = profile + "  " + deletebtn + " " + addwatchlist+" "+switchbutton;
						
				return_data.push({
						'id': json.data[i].id,
						'name': json.data[i].name,
						'fatherName': json.data[i].fatherName,
						'age': json.data[i].age,
						'gender': json.data[i].gender,
						'address': json.data[i].address,
						'type': json.data[i].moType,
						'category': json.data[i].category,
						'aadhar': json.data[i].aadharNumber,
						'action': action
					});
			}
			return return_data;
		}
	},
	"columns": [
		{'data': 'id'},
		{'data': 'name'},
		{'data': 'fatherName'},
		{'data': 'age'},
		{'data': 'gender'},
		{'data': 'address'},
		{'data': 'type'},
		{'data': 'category'},
		{'data': 'action'}
	],
	fnDrawCallback:function (oSettings) {
		console.log("after table create");
		var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));

		elems.forEach(function(html) {
			var switchery = new Switchery(html);
		});
	}
});

i can get check box in every row, but unable to get the switchery working, all of the data for the datatable are coming from ajax request.

@harsh-r-dave
Copy link
Author

@AnuroopSuresh well, I haven't tried above code with ajax. if your fnDrawCallback is being called after the data is loaded through ajax and populated in the table, above code should be placed under that callback. or try renaming the fnDrawCallback to drawCallback since as far as I am aware, fnDrawCallback is for older versions of datatable. problem with drawCallback is, it will be called every time datatable is drawn which also includes sorting the columns (you may not want to initialize the switch every time, it will probably duplicate them)

best options I could think of is (not tested), createdRow callback which will be triggered after a row is created in the table. you can then find your checkbox within that row and initialize it.
https://datatables.net/reference/option/createdRow

"createdRow": function (row, data, index) {
         // find checkboxes here
        // init switch here
       
        // may be something like this (again, not tested)
        var switchElem = Array.prototype.slice.call($(row).find('.js-switch'));
        switchElem.forEach(function (html) {
            var switchery = new Switchery(html, { color: '#0275D8', secondaryColor: '#dee2e6' });
        });
}

Alternatively, you could try using initComplete callback which will run after the table is fully initialized (there might be a flick while initializing switches).

https://datatables.net/forums/discussion/48103/callback-function-every-time-new-data-is-completely-loaded
https://datatables.net/reference/option/initComplete
https://datatables.net/reference/api/
https://datatables.net/reference/option/

I haven't worked with datatables a lot, so unfortunately I can't suggest best ways for it.

@mssadewa
Copy link

Hi @harsh18594
Thank you, I've tried it and works.
You've save my time. I've try to figure it out for more than 6 hours. the createdRow callback is a key!
Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants