0

I have an input to search ids, you can type one or more letters and the first id who starts by that letter/letters will be filled inside the input, but as you can see, it's still not intuitive:

Type a or ab to test the snippet.

$(document).ready(Hi);
function Hi(){
        var keys = "";
        $("input").keyup(function(e){
                var inp = $(this);
                var wk = event.which;
                if(wk!=8){                                               //if not pressed backspace
                        if((wk >= 65 && wk <= 120) && (wk != 32 && wk != 0)){  //allow just letters
                            keys = keys+ e.key;
                        }
                        inp.val($("p[id^="+keys+"]").attr("id"))
                        //inp.val(inp.val().slice(keys.length));  //this is just the
                        //inp.val(keys+(inp.val().select()));     //idea, but wont work
                }else{
                        inp.val("");
                        keys="";
                }
        });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"/>

<p id="apple"></p>
<p id="abocado"></p>
<p id="abanico"></p>

The idea is to view just the typed letter/letters normally, and select the rest of the word to let the user knows he can keep typing after his typed text and not after the entire word who was filled in by the program.

Something like this:

enter image description here

Is there a way to make this work? I'm accepting css too.

EDIT

Thanks to this, I've made this work:

$(document).ready(Hi);
function Hi(){
        var keys = "";
        $("input").keyup(function(e){
                var inp = $(this);
                var wk = event.which;
                if(wk!=8){
                        if((wk >= 65 && wk <= 120) && (wk != 32 && wk != 0)) { 
                            keys = keys+ e.key;
                        }
                        var par = $("p[id^="+keys+"]").attr("id");
                        inp.val(par)
                        letSelect(inp[0],keys.length,par.length);
                }else{
                        inp.val("");
                        keys="";
                }
        });
}

function letSelect(input, startPos, endPos) {
    input.focus();
    if (typeof input.selectionStart != "undefined") {
        input.selectionStart = startPos;
        input.selectionEnd = endPos;
    } else if (document.selection && document.selection.createRange) {
        input.select();
        var range = document.selection.createRange();
        range.collapse(true);
        range.moveEnd("character", endPos);
        range.moveStart("character", startPos);
        range.select();
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text"/>

<p id="apple"></p>
<p id="abocado"></p>
<p id="abanico"></p>

0 Answers0