18Apr

List.js search issue with string using comma or dash listObj.search

List.js is a great JavaScript library that adds search, sort, filters, and flexibility to plain HTML lists, tables, or anything. I had issues filtering from a dropdown only for some values. It took me a while to figure out what was wrong, as most filters worked.

https://listjs.com/api/#search

List.js search method: searching string with values including “,” or “-” return false. Simple bug fix

I have a web page listing jobs, job results can be filtered by free search, job location dropdown and job department.

Here is an extract of my JavaScript code

var options = {
	page: 10, 
	pagination: true,
	searchDelay: 300,
	valueNames: [ 
		'job-title', 
		'job-contract', 
		{ name: 'job-location', attr: 'data-location' },
		{ name: 'job-department', attr: 'data-department' },
	],
};
var listObj = new List('listjobs', options);

To filter listing, we have listeners on a “#jobdepartment” dropdown. There are 3 different values can be combined for the search in my example.

$('#jobdepartment').on('change', function(){
	const keyword_val = $('#jobkeywords').val().trim();
	const location_val = $('#joblocation').val().trim();
	let department_val = $(this).val().trim();

	// line to fix values with - or ,
	department_val = department_val.replaceAll("-", "").replaceAll(",", "");

	listObj.search(keyword_val+" "+location_val+" "+department_val);
});

The issue

Job department could contain values such as “Designer 2D, 3D” or “Lead Designer – Packaging“. The search for this exact text value returns false, even if this exact text is present in the job listing copy. While values such as “Design & Development” worked fine.

The solution

The values searched in the text are only words. To fix this issue, I just needed to remove all instances of specific special characters. In my case – or , using a .replaceAll for each wished character in the searched value.

If this helped you, leave a little comment. Thanks.

Subscribe
Notify of

0 Comments
Inline Feedbacks
View all comments