Reputation: 523
I have an array of devices, each device has own unique id, I wish to make searchBox which will filter by this id. So far I managed it partly, so it checks if character from input match character from device-id. However not in way I would want that, example below:
id =35678; input.value = 5
it shouldn't work as first character is 3
id = 35679; input.value= 35
it should work as first character is same
Problem is in match/include function, but no really idea how to replace it to make it work
input_box.addEventListener('keyup', function(){
var search_result = this.value;
var device = document.querySelectorAll('[device_id]')
var array_of_devices = [];
for (var i = 0; i < device.length; i++) {
array_of_devices.push(device[i].getAttribute('device_id'))
}
array_of_devices.forEach(el => {
if (!el.match(search_result)) {
var not_matched = document.querySelector(`[device_id="${el}"]`)
not_matched.style.display = "none"
} else {
var matched = document.querySelector(`[device_id="${el}"]`)
matched.style.display = "block"
}
})
})
Upvotes: 0
Views: 49
Reputation: 2510
Notice each id in array should be string
const ids = ['3575', '5555']
const found = value => ids.filter(i => i.indexOf(value, 0) === 0)
console.log(found(5));
console.log(found(35));
Upvotes: 0
Reputation: 37755
You can use startsWith instead of match
let arr = ['35678', '451234', '45454', '56565']
let find = (value) =>{
return arr.filter(id=> id.startsWith(value))
}
console.log(find(5))
console.log(find(35))
console.log(find(46))
Upvotes: 2
Reputation: 36703
Instead of using .match
you can simply use .indexOf
and check the index, if it 0 then the entered string is matching the device name from the begining.
array_of_devices.forEach(el => {
// Condition below is changed to use indexOf
if (el.indexOf(search_result) === 0) {
var not_matched = document.querySelector(`[device_id="${el}"]`)
not_matched.style.display = "none"
} else {
var matched = document.querySelector(`[device_id="${el}"]`)
matched.style.display = "block"
}
});
I would suggest you to build a string of device elements based on the search string and add it to your DOM instead of modifying the display properties. This is costing you a bunch of DOM operations which is computationally heavy.
Upvotes: 1