Javascript Autocomplete email's domain using jQuery UI

不问归期 提交于 2019-11-29 12:14:39

The select function is assigning the resultant value with this.value =. However it is replacing the input value completely rather than appending it with the drop down value.

Without a great deal of testing the following, simplified function seems to work as required:

select: function( event, ui ) {
    this.value = this.value.substring(0, this.value.indexOf('@') + 1) + ui.item.value;
    return false;
}

This is taking the first part of the already entered value, for example foo@ for the input foo@ya and then adding on the value of the selected item from the drop down.

You may want to trigger the dropdown when someone enters the @ symbol (seems more intuitive to me) and if so, this function may also need modifying to correctly extract the user entered value.

Here is the complete code:

$(function() {
    var availableTags = [
        "Yahoo.com",
        "Gmail.com"
    ];
    function extractLast( val ) {
        if (val.indexOf("@")!=-1){
            var tmp=val.split("@");
            console.log(tmp[tmp.length-1]);
            return tmp[tmp.length-1];
        }
        console.log("returning empty");
        return "";
    }

    $( "#tags" )
        // don't navigate away from the field on tab when selecting an item
        .bind( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                    $( this ).data( "autocomplete" ).menu.active ) {
                event.preventDefault();
            }
        })
        .autocomplete({
            minLength: 1,
            source: function( request, response ) {
                        var mail = extractLast(request.term);
                        if(mail.length<1){return;}
                        var matcher = new RegExp( "^" + mail, "i" );
                        response( $.grep( availableTags, function( item ){
                            return matcher.test( item );
                        }));
             },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {
                var terms = this.value.split(", ");
                // remove the current input
                var ml=terms[terms.length-1].split("@")[0];
                terms.pop();
                // add the selected item
                terms.push( ml+"@"+ui.item.value );
                // add placeholder to get the comma-and-space at the end
                terms.push( "" );
                this.value = terms.join( ", " );
                return false;
            }
        });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!