簡體   English   中英

Bootstrap typeahead在MVC 5中不起作用

[英]Bootstrap typeahead not working in MVC 5

在我的mvc項目中,IAM嘗試實現自動完成功能,但無法正常工作(打字頭),我所做的一切都正確,但無法實現。 下面是我的代碼。 誰能幫忙

<script type="text/javascript">
$(document).ready(function () {

    $("#Search").typeahead({
        source: function (query, process) {
            var countries = [];
            map = {};

            // This is going to make an HTTP post request to the controller
            return $.post('/Registration/GetPossibleLocations', { query: query }, function (data) {

                // Loop through and push to the array
                $.each(data, function (i, country) {
                    map[country.Name] = country;
                    countries.push(country.Name);
                });

                // Process the details
                process(countries);
            });
        },
        updater: function (item) {
            var selectedShortCode = map[item].ShortCode;

            // Set the text to our selected id
            $("#details").text("Selected : " + selectedShortCode);
            return item;
        }
    });

});

<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js" type="text/javascript">     </script>
<script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js" type="text/javascript"></script>

<div>
    <input type="text" id="Search" data-provide="typeahead" placeholder="Country" autocomplete="off" />    
        </div>

typeahead()等待至少兩個參數。 第一個參數是選項數組,然后您可以定義多個數據集。 source必須在數據集中定義。

請參閱以下用法: https : //github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md#usage

如文檔所述, source必須計算建議集(即JavaScript對象數組 )以進行查詢。 您正在傳遞字符串數組。 除此之外,您還必須設置displayKey

如果您在文本字段中寫入內容,則source將在第一次執行。

我為您准備了一個小提琴: http : //jsfiddle.net/dtengeri/EhJvB/

您的代碼應如下所示:

<script type="text/javascript">
$(document).ready(function () {
  // Notice the first empty object. You can specify options in it.
  $("#Search").typeahead({}, {
      displayKey: 'Name',
      source: function (query, process) {
          var countries = [];
          map = {};

          // This is going to make an HTTP post request to the controller
          return $.post('/Registration/GetPossibleLocations', { query: query }, function (data) {

              // Loop through and push to the array
              $.each(data, function (i, country) {
                  map[country.Name] = country;
                  // You have to create an array of JS objects. 
                  // Typeahead will use the displayKey to fetch data from the object.
                  countries.push({'Name': country.Name});
              });

              // Process the details
              process(countries);
          });
      },
      ...        
  });

});

我更喜歡使用獵犬的集成來獲取數據源。 這是有關我如何使用它的示例:

捆綁:

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/layoutScriptsBundle").Include(
            "~/_js/_lib/jquery/jquery-{version}.js",
            "~/_js/_lib/bootstrap/bootstrap.js",
            "~/_js/_lib/typeahead.js/typeahead.bundle.js",
            "~/_js/_lib/handlebars.js/handlebars-v1.3.0.js"));

        bundles.Add(new StyleBundle("~/bundles/css/libs/layoutStylesBundle").Include(
            "~/_css/_lib/bootstrap/bootstrap.css",
            "~/_css/_lib/typeahead.js/typeahead.js-bootstrap.css"));
    }
}

JavaScript:

<script>
    window.siteNS = window.siteNS || {};
    jQuery(document).ready(function ($) {
        siteNS.typeaheadRemoteUrl = '@Url.ActionFor((ExampleController c) => c.GetTypeaheadData(null))?q=%QUERY';

        var myTypeaheadData = new Bloodhound({
            datumTokenizer: function (d) {
                return Bloodhound.tokenizers.whitespace(d.value);
            },
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            remote: {
                url: siteNS.typeaheadRemoteUrl,
                rateLimitWait: 250,
                ajax: { cache: false }
            }
        });

        myTypeaheadData.initialize();

        $('#myTypeahead').typeahead({
            autoselect: true,
            highlight: true,
            hint: true,
            minLength: 1
        }, {
            source: myTypeaheadData.ttAdapter(),
            name: 'myTypeaheadDatasetName',
            displayKey: 'ItemName',
            templates: {
                empty: '',
                footer: '',
                header: '',
                suggestion: Handlebars.compile('<p>{{ItemName}} - {{ItemID}}</p>')
            }
        });
    });
</script>

HTML:

<div class="form-group">
    <label class="control-label col-lg-4">Search/Autocomplete</label>
    <div class="col-lg-8 myTypeaheadContainer">
        <input id="myTypeahead" type="text" class="form-control">
        <span class="help-block">Using typeahead.js</span>
    </div>
</div>

嘗試這個

please remove autocomplete="off" from tag  


    <div>
    <input type="text" id="Search" data-provide="typeahead" placeholder="Country" />    
    </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM