So I created a little search box that will filter out a select list of options as you type. I also wanted it to filter through the list when you paste into the search box but it doesn’t seem to work.
The issue happens when you use your mouse, right click and click paste. ctrl+v works just fine.
I also notice it works if you paste in twice or if the text box already has text in it and you highlight over it and replace the current text in the box. Or you paste in then start typing (as the onkeyup function will then start taking over)
So for example with my code below simply copy the word "yellow" or another color, right click into the search box, and click paste. It doesn’t filter.
Any idea on how to fix this? Thanks!
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInputz69");
filter = input.value.toUpperCase();
div = document.getElementById("authorCC");
a = div.getElementsByTagName("option");
for (i = 0; i < a.length; i++) {
txtValue = a[i].textContent || a[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
<div id="authorCC">
<input type="text" class="affsearch" placeholder="Search.." id="myInputz69" onkeyup="filterFunction()" onpaste="filterFunction()">
<select class="affselect" name="authorCC" id="authorCC" size="5" >
<option value="-">-</option>
<option value="blue">blue</option>
<option value="green">green</option>
<option value="red">red</option>
<option value="yellow">yellow</option>
</select>
</div>
>Solution :
While I can’t tell you exactly why onpaste doesn’t work in this context, why not just eliminate the need to do two separate event handlers and instead hook the input event? It will work with (a) key events leading to changes to the input value, (b) a paste event invoked with CTRL–V, and (c) a paste event invoked via the contextual menu:
function filterFunction() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInputz69");
filter = input.value.toUpperCase();
div = document.getElementById("authorCC");
a = div.getElementsByTagName("option");
for (i = 0; i < a.length; i++) {
txtValue = a[i].textContent || a[i].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
a[i].style.display = "";
} else {
a[i].style.display = "none";
}
}
}
<div id="authorCC">
<input type="text" class="affsearch" placeholder="Search.." id="myInputz69" oninput="filterFunction()">
<select class="affselect" name="authorCC" id="authorCC" size="5" >
<option value="-">-</option>
<option value="blue">blue</option>
<option value="green">green</option>
<option value="red">red</option>
<option value="yellow">yellow</option>
</select>
</div>