是否有可能通过输入使用combobox jQuery自动选择选项

时间:2016-09-19 02:18:43

标签: javascript jquery combobox autocomplete jquery-ui-autocomplete

我使用jQuery来制作组合框输入,一切运行良好,这是我的代码

 $('#id').combobox({});

这是我的组合框输入

this is the combobox input mockup

问题是当组合框输入表单必须自动填充时,

例如,

在组合框中输入的值是" 45",因此结果显示喜欢" 45"的数据,包括" 453" AND" 454",对于这种情况,组合框不是自动完成的,因为像" 45"不仅仅是一个,我的问题是如果输入的值是" 453",组合框jQuery将自动完成该值,组合框自动完成的原因,因为没有像" 453"除了自我,在.autocomplete({})可能,使用此代码

            open: openUser,

    function openUser(event, ui)
{
    // Try to select the first one if it's the only one
    var $children = jQuery(this).data('autocomplete').menu.element.children();
    if ($children.size() == 1)
    {
        $children.children('a').mouseenter().click();
    }
}

我怎样才能将代码实现到combobox jQuery而不是.autocomplete,

提前致谢。

1 个答案:

答案 0 :(得分:1)

是的你可以通过输入自动选择选项这里是例子,当你输入一些东西并且结果包含一个项目时,这里的选项会被自动选择

我从https://jqueryui.com/autocomplete/#combobox采取了示例并进行了修改。

我更新了_source函数的代码。



$( function() {
    $.widget( "custom.combobox", {
		options: {
			previousValue:""
		},
      _create: function() {
        this.wrapper = $( "<span>" )
          .addClass( "custom-combobox" )
          .insertAfter( this.element );
 
        this.element.hide();
        this._createAutocomplete();
        this._createShowAllButton();
      },
 
      _createAutocomplete: function() {
        var selected = this.element.children( ":selected" ),
          value = selected.val() ? selected.text() : "";
 
        this.input = $( "<input>" )
          .appendTo( this.wrapper )
          .val( value )
          .attr( "title", "" )
          .addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
          .autocomplete({
            delay: 0,
            minLength: 0,
            source: $.proxy( this, "_source" )
          })
          .tooltip({
            classes: {
              "ui-tooltip": "ui-state-highlight"
            }
          });
 
        this._on( this.input, {
          autocompleteselect: function( event, ui ) {
            ui.item.option.selected = true;
            this._trigger( "select", event, {
              item: ui.item.option
            });
          },
 
          autocompletechange: "_removeIfInvalid"
        });
      },
 
      _createShowAllButton: function() {
        var input = this.input,
          wasOpen = false;
 
        $( "<a>" )
          .attr( "tabIndex", -1 )
          .attr( "title", "Show All Items" )
          .tooltip()
          .appendTo( this.wrapper )
          .button({
            icons: {
              primary: "ui-icon-triangle-1-s"
            },
            text: false
          })
          .removeClass( "ui-corner-all" )
          .addClass( "custom-combobox-toggle ui-corner-right" )
          .on( "mousedown", function() {
            wasOpen = input.autocomplete( "widget" ).is( ":visible" );
          })
          .on( "click", function() {
            input.trigger( "focus" );
 
            // Close if already visible
            if ( wasOpen ) {
              return;
            }
 
            // Pass empty string as value to search for, displaying all results
            input.autocomplete( "search", "" );
          });
      },
 
      _source: function( request, response ) {
        var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
		var result = [];
        result = this.element.children( "option" ).map(function() {
          var text = $( this ).text();
          if ( this.value && ( !request.term || matcher.test(text) ) )
            return {
              label: text,
              value: text,
              option: this
            };
        }); 
		if(result.length == 1 && request.term.length > this.options.previousValue.length ){
				result[0].option.selected = true;
				this._trigger( "select", null, {
					item: result[0].option
				});
				this.input.val(result[0].label);
				this.options.previousValue = result[0].label;
		}else{
			this.options.previousValue = request.term;		
		}
		response(result);
		
      },
 
      _removeIfInvalid: function( event, ui ) {
 
        // Selected an item, nothing to do
        if ( ui.item ) {
          return;
        }
 
        // Search for a match (case-insensitive)
        var value = this.input.val(),
          valueLowerCase = value.toLowerCase(),
          valid = false;
        this.element.children( "option" ).each(function() {
          if ( $( this ).text().toLowerCase() === valueLowerCase ) {
            this.selected = valid = true;
            return false;
          }
        });
 
        // Found a match, nothing to do
        if ( valid ) {
          return;
        }
 
        // Remove invalid value
        this.input
          .val( "" )
          .attr( "title", value + " didn't match any item" )
          .tooltip( "open" );
        this.element.val( "" );
        this._delay(function() {
          this.input.tooltip( "close" ).attr( "title", "" );
        }, 2500 );
        this.input.autocomplete( "instance" ).term = "";
      },
 
      _destroy: function() {
        this.wrapper.remove();
        this.element.show();
      }
    });
});

$(document).ready(function(){
	$( "#combobox" ).combobox();
     
     $( "#toggle" ).on( "click", function() {
      $( "#combobox" ).toggle();
    });
  
});
&#13;
.custom-combobox {
    position: relative;
    display: inline-block;
  }
  .custom-combobox-toggle {
    position: absolute;
    top: 0;
    bottom: 0;
    margin-left: -1px;
    padding: 0;
  }
  .custom-combobox-input {
    margin: 0;
    padding: 5px 10px;
  }
&#13;
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>

<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>

<div class="ui-widget">
  <label>Your preferred programming language: </label>
  <select id="combobox">
    <option value="">Select one...</option>
    <option value="ActionScript">ActionScript</option>
    <option value="AppleScript">AppleScript</option>
    <option value="Asp">Asp</option>
    <option value="BASIC">BASIC</option>
    <option value="C">C</option>
    <option value="C++">C++</option>
    <option value="Clojure">Clojure</option>
    <option value="COBOL">COBOL</option>
    <option value="ColdFusion">ColdFusion</option>
    <option value="Erlang">Erlang</option>
    <option value="Fortran">Fortran</option>
    <option value="Groovy">Groovy</option>
    <option value="Haskell">Haskell</option>
    <option value="Java">Java</option>
    <option value="JavaScript">JavaScript</option>
    <option value="Lisp">Lisp</option>
    <option value="Perl">Perl</option>
    <option value="PHP">PHP</option>
    <option value="Python">Python</option>
    <option value="Ruby">Ruby</option>
    <option value="Scala">Scala</option>
    <option value="Scheme">Scheme</option>
  </select>
</div>
<button id="toggle">Show underlying select</button>
&#13;
&#13;
&#13;