Mr. Developer Mr. Developer - 1 month ago 9
Javascript Question

How can i convert attribute data to lower case using JavaScript only?

I'm trying to make auto suggest search. Its working fine only thing i want to improve is that upper and lower case values. I have below

li
list

<input type="text" id="filter-search" />

<ul>
<li filter-value="One Is">One Is (Uppercase)</li>
<li filter-value="one is">one is (Lowercase)</li>
<li filter-value="two">Two</li>
<li filter-value="three">Three</li>
<li filter-value="four">Four</li>
<li filter-value="five" >Five</li>
<li filter-value="six">Six</li>
<li filter-value="seven">Seven</li>
<li filter-value="eight">Eight</li>
<li filter-value="nine">Nine</li>
<li filter-value="ten" >Ten</li>
</ul>





var inputId = 'filter-search';
var itemsData = 'filter-value';
var displaySet = false;
var displayArr = [];

function getDisplayType(element) {
var elementStyle = element.currentStyle || window.getComputedStyle(element, "");
return elementStyle.display;
}

document.getElementById(inputId).onkeyup = function() {
var searchVal = this.value.toLowerCase();
var filterItems = document.querySelectorAll('[' + itemsData + ']');
for(var i = 0; i < filterItems.length; i++) {
if (!displaySet) {
displayArr.push(getDisplayType(filterItems[i]));
}
filterItems[i].style.display = 'none';
if(filterItems[i].getAttribute('filter-value').toLowerCase().indexOf(searchVal.toLowerCase()) >= 0) {
filterItems[i].style.display = displayArr[i];
}
}
displaySet = true;
}


The first
li
is not searchable, because it has upper case value, here is code (its few line) Can anyone kindly guide me that how can i fix the issue. I would like to appreciate.

Answer

If you want to do a case-insensitive search, convert both strings to lowercase before comparing:

if(filterItems[i].getAttribute('filter-value').toLowerCase().indexOf(searchVal) >= 0) {

You could, of course, optimize this by setting the data- attribute value to a lowercase value on the server.

Comments