jquery autocomplete auto fill field with 1st value and highligh added part

后端 未结 4 874
野的像风
野的像风 2020-12-31 12:29

im using jqueryui autocomplete plugin with following code

$(this).autocomplete({
                source: function(request, response) {
                    $.         


        
4条回答
  •  悲哀的现实
    2020-12-31 13:08

    Works great! On mobile devices: not so much though. The first item from the menu gets selected automatically after it shows up for the first time.

    To avoid this, I came up with this solution for mobile devices:

        close: function( event, ui ) {
            let firstElement =  $(this).data("uiAutocomplete").menu.element[0].children[0]
               , inpt = $(this)
               , original = inpt.val()
               , firstElementText = $(firstElement).text();
    
            /*
               here we want to make sure that we're not matching something that doesn't start
               with what was typed in 
            */
            if(firstElementText.toLowerCase().indexOf(original.toLowerCase()) === 0){
                inpt.val(firstElementText);//change the input to the first match
    
                inpt[0].selectionStart = original.length; //highlight from end of input
                inpt[0].selectionEnd = firstElementText.length; //highlight to the end
                $("#zoominmap").click(); // trigger click on mobile
            }
        },
    

    close instead open - and a click event on a button (#zoominmap) after the highlighting.

    I have the whole code wrapped in this media query btw:

    if (window.matchMedia('only screen
     and (min-device-width:120px)
     and (max-device-width:767px)').matches) {
    /*
    mobile
    */
    } else {
    /*
    desktop
    */
    }
    

提交回复
热议问题