You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让jQuery UI Autocomplete Combobox选中后显示option的value值

修改jQuery UI Autocomplete Combobox,选中选项后输入框显示对应Value值

当前你的Combobox组件下拉显示选项的描述文本(如Desc1、Desc2),但选中后输入框仍显示描述文本,要实现选中后显示对应的Value值(如Value1、Value2),需要修改以下3处关键代码:

1. 调整数据源返回的value字段

在_source方法中,将返回对象的value字段改为对应option的value属性,保留label为描述文本,这样下拉列表显示描述,选中后输入框自动填充Value值:

_source: function( request, response ) {
  var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
  response( this.element.children( "option" ).map(function() {
    var text = $( this ).text();
    if ( this.value && ( !request.term || matcher.test(text) ) )
      return {
        label: text, // 下拉显示描述文本
        value: this.value, // 选中后输入框显示Value值
        option: this
      };
  }) );
},

2. 修正初始输入框的赋值逻辑

在_createAutocomplete方法中,初始输入框的值从选中项的文本改为选中项的Value,确保页面加载时输入框显示正确的初始值:

_createAutocomplete: function() {
  var selected = this.element.children( ":selected" ),
    value = selected.val() ? selected.val() : ""; // 从selected.text()改为selected.val()

  this.input = $( "<input>" )
    .appendTo( this.wrapper )
    .val( value )
    // 后续代码保持不变
},

3. 更新无效值校验逻辑

在_removeIfInvalid方法中,因为输入框现在存储的是Value值,所以校验时要匹配option的value属性而非文本:

_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() {
    // 从$(this).text().toLowerCase()改为this.value.toLowerCase()
    if ( this.value.toLowerCase() === valueLowerCase ) {
      this.selected = valid = true;
      return false;
    }
  });

  // 后续代码保持不变
},

修改后的完整代码

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Autocomplete - Combobox</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <style>
  .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;
  }
  </style>
  <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
  <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
  <script>
  $( function() {
    $.widget( "custom.combobox", {
      _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.val() : "";

        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: this._source.bind( this )
          })
          .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" );
        response( this.element.children( "option" ).map(function() {
          var text = $( this ).text();
          if ( this.value && ( !request.term || matcher.test(text) ) )
            return {
              label: text,
              value: this.value,
              option: this
            };
        }) );
      },

      _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.value.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();
      }
    });

    $( "#combobox" ).combobox();
    $( "#toggle" ).on( "click", function() {
      $( "#combobox" ).toggle();
    });
  } );
  </script>
</head>
<body>

<div class="ui-widget">
  <select id="combobox">
    <option value>Select one...</option>
    <option value="Value1">Desc1</option>
    <option value="Value2">Desc2</option>
  </select>
</div>


</body>
</html>

内容的提问来源于stack exchange,提问作者Trombone0904

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 20:31:03