I'm developing a autocomplete solution with a database search based on typing events (onkeyup) that the user inputs in a <h:inputText />
.
The problem is that i have two pre-conditions that the application must attend to do a server-side search:
- The text informed is >= 3 and <= 6 characters
- User stopped typing for a few miliseconds (Preventing overload the server with to much search)
Without the item 2) it's pretty simple do solve that just adding something like onkeyup="return checkInputs(this.value)
and returning false every time that the text input lenght is < 3 or > 6.
But to attend item 2) it seems that I should use Javascript setTimeout , in which this case makes use of a callback, i.e, i can not use any return to meet the event the onkeyup of my input text .
I've been struggling with this problem for a few days, and i don't have any clues how can i solve this, just because i'm limited with my actual stack (JSF 2.1 without any additional library such as PrimeFaces or OmniFaces and Jquery 1.3)
Html Code:
<h:inputText id="text" alt="text"
maxlength="6" size="6" title="text"
value="#{managedBean.searchText}"
onkeyup="return checkInputs(this.value)">
<f:ajax listener="#{managedBean.doSearch}" execute="@this"
event="keyup" render="form:searchResult" />
</h:inputText>
Javascript:
function checkInputs(value) {
let cnsAnterior = sessionStorage.getItem('previousValue');
sessionStorage.setItem('previousValue', value);
if((value.length >= 3 && value.length <= 6) && (previousValue != value)){
return true;
}
return false;
}
Some snippet i've found at this website, for preventing search until user has stopped typing:
// Get the input box
var textInput = document.getElementById('test-input');
// Init a timeout variable to be used below
var timeout = null;
// Listen for keystroke events
textInput.onkeyup = function (e) {
// Clear the timeout if it has already been set.
// This will prevent the previous task from executing
// if it has been less than <MILLISECONDS>
clearTimeout(timeout);
// Make a new timeout set to go off in 800ms
timeout = setTimeout(function () {
console.log('Input Value:', textInput.value);
}, 500);
};
Is there any way, using JSF, that i can attend this two clauses ? Only do a server search when user typed at least 3 characters AND stopped type at few milisseconds ?
Thanks in advance.