开发者

Jquery autocomplete - change the response to <tab> and <enter> keystrokes

I have a functioning autocomplete box on my site that I want to work like the 'Tags' autocomplete in SO.

Desired behavior

After you see a drop-down of suggestions, hitting tab or enter on the keyboard 'accepts' the highlighted option, adds a space, and moves the focus to the end of the line for entering the next tag.

Current behavior

After you get the drop-down, hitting tab or enter replaces the entire contents of the textbox with the current suggestion, and the cursor selects all the text (instead of inserting a space and pointing at the end of the line).

How can I achieve this response?


This is my javascript:

$(function() { 
$( "#tags-field" )
    // 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({
      source: function( request, response ) {
        $.ajax({
            url: "<%= autocomplete_tags_name_questions_url %&g开发者_开发问答t;",
            dataType: "jsonp",
            data: {
                featureClass: "P",
                style: "full",
                maxRows: 12,
                name_startsWith: request.term
            },
            success: function( data ) {
                alert("Hi!"),
                response( $.map( data, function( item ) {
                    return {
                        label: item.name, //+ (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
                        value: item.name
                    }
                }));
            }
        });
      },
      minLength: 2
  });
});

First, the .bind part at the top doesn't seem to be working. How do I reconcile the code here with the code above?


Check out the multiple values demo.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜