17

ここにhttp://jqueryui.com/autocomplete/のコードがありますが、本当にうまく機能しますが、テキストビューで選択したアイテムの値を取得する方法が見つかりません。このようなことを試しましたが、機能しません

<script>
$(document).ready(function () {
    $('#tags').change(function () {
        $('#tagsname').html('You selected: ' + this.value);
    }).change();
});
</script>

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Autocomplete - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css" />
  <script>
  $(function() {
    var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ];
    $( "#tags" ).autocomplete({
      source: availableTags
    });
  });
  </script>
<script>
$(document).ready(function () {
    $('#tags').change(function () {
        $('#tagsname').html('You selected: ' + this.value);
    }).change();
});
</script>
</head>
<body>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags" />
  <div id="tagsname"></div>
</div>


</body>
</html>
4

5 に答える 5

43

オートコンプリートが値を変更すると、change イベントではなくautocompletechangeイベントが発生します

$(document).ready(function () {
    $('#tags').on('autocompletechange change', function () {
        $('#tagsname').html('You selected: ' + this.value);
    }).change();
});

デモ:フィドル

別の解決策は、入力がぼやけている場合にのみ変更イベントがトリガーされるため、selectイベントを使用することです。

$(document).ready(function () {
    $('#tags').on('change', function () {
        $('#tagsname').html('You selected: ' + this.value);
    }).change();
    $('#tags').on('autocompleteselect', function (e, ui) {
        $('#tagsname').html('You selected: ' + ui.item.value);
    });
});

デモ:フィドル

于 2013-10-30T06:14:42.483 に答える
23

より一般的に質問に答えるには、答えは次のとおりです。

select: function( event , ui ) {
    alert( "You selected: " + ui.item.label );
}

完全な例:

$('#test').each(function(i, el) {
    var that = $(el);
    that.autocomplete({
        source: ['apple','banana','orange'],
        select: function( event , ui ) {
            alert( "You selected: " + ui.item.label );
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>

Type a fruit here: <input type="text" id="test" />

于 2014-10-28T21:07:12.143 に答える