Bootstrap Tagsinput多选组件Typeahead功能无法实现求助
Let's walk through the issues in your code and fix them step by step to get the Typeahead query working properly:
Key Problems in Your Current Implementation
- Wrong Input Target: You're selecting
$('input[type="text"]')directly, but Bootstrap Tagsinput wraps its input in a custom container. You need to target the specific input element created by the tagsinput component. - Broken API URL: The way you're inserting the
queryvariable into your URL is incorrect — right now it's being treated as literal text ("+query+") instead of a dynamic value. - Unprocessed API Data: The Typeahead
sourcefunction requires you to pass fetched suggestions to theprocesscallback to display them. Your current code only logs data to the console without feeding it to Typeahead.
Corrected Code
<div class="bs-example"> <select multiple data-role="tagsinput"> {% for tag in result['tag'] %} <option value="{{tag}}" selected="selected">{{tag}}</option> {% endfor %} </select> <script> // Target the internal input element created by Bootstrap Tagsinput $('.bootstrap-tagsinput input').typeahead({ source: function (query, process) { // Fix URL interpolation using template literals for clean variable insertion return $.getJSON(`http://localhost:9450/a=query&text=${query}*:PTN_LABEL&print=fields&printfields=PTN_LABEL&matchdatabase=xxxx&responseformat=json`, { query: query }, function (data) { // Adjust this line to match your API's actual data structure // Assuming your API returns an array of objects with a PTN_LABEL property const tagSuggestions = data.map(item => item.PTN_LABEL); // Pass the processed suggestions to Typeahead to display them process(tagSuggestions); console.log(data); }); } }); </script> </div>
Important Additional Checks
- Script Load Order: Ensure your dependencies are loaded in this exact sequence:
- jQuery
- Typeahead.js
- Bootstrap Tagsinput
- Your custom script
- API Response Structure: Double-check your API's returned data format. If suggestions are nested under a key like
resultsinstead of being a top-level array, update thedata.map(...)line to match (e.g.,data.results.map(...)). - Tagsinput Initialization: If you're initializing Tagsinput via JavaScript instead of the
data-roleattribute, make sure that initialization runs before you attach the Typeahead plugin.
内容的提问来源于stack exchange,提问作者Vinay Joseph
相关产品推荐
相关产品推荐

