原创js自动补全---auotocomplete

        if ($("input.autocomplete_input").length > 0) {
            $("input.autocomplete_input").bind('focus keydown', function (event) {
                if ($(this).parent('div').prev('div').find('div.help-block').html() != '') {
                    $(".autocomplete-menu").css('top','167px');
                } else {
                    $(".autocomplete-menu").css('top','142px');
                }
                var value = $(this).val();
                autocomplete('<?=Url::toRoute(['ajax-auto-complete'])?>', value, 1, this.getAttribute('name'));
            });
            $("input.autocomplete_input").on('blur', function (event) {
                window.setTimeout(function(){$(".autocomplete-menu").empty();$(".autocomplete-menu").hide();},200);
            });
        }


function sureValue(obj, inputName) {
    var userId = $(obj).attr('data-id');
    var userName = $(obj).attr('data-name');
    $("input[name='" + inputName + "']").val(userName);
    $("#autocomplete-hidden-id").val(userId);
}

function autocomplete(url, data, type, inputName) {
    $(".autocomplete-menu").empty();
    jQuery.ajax({
        type: 'POST',
        data: {'key': data, 'type': type},
        url: url,
        dataType: 'json',
        success: function (da) {
            if (da.length > 0) {
                for (var p in da) {
                    var name = da[p].realname ? da[p].realname : da[p].username;
                    var chilren = '<a class="autocomplete-dataset " onclick="sureValue(this, \'' + inputName + '\')" data-id="' + da[p].id + '" data-name="' + name + '">' + da[p].username + '---' + da[p].realname + '</a>';
                    $(".autocomplete-menu").append(chilren);
                }
            }
            $(".autocomplete-menu").show();
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            // alert(XMLHttpRequest.status);
            // alert(XMLHttpRequest.readyState);
            // alert(textStatus);
        }
    });
}

 

posted @ 2017-12-06 10:29  yangboom  阅读(412)  评论(0编辑  收藏  举报
TOP