[英]How to ignore trailing white spaces in text input when comparing to datalist options?
I am using AJAX to pull potential matching results from the server and append the options to the datalist on the search bar on every key-up event. 我正在使用AJAX从服务器中提取潜在的匹配结果,并在每次键入事件时将选项附加到搜索栏上的数据列表中。 The problem is if the user adds trailing white spaces, the datalist collapses and doesn't show the matching results. 问题是,如果用户添加尾随空格,则数据列表将折叠并且不显示匹配结果。 How can I force the datalist to remain open if there is a matching results with additional trailing white spaces? 如果有匹配的结果以及其他尾随空格,如何强制数据列表保持打开状态?
The behavior I describe is illustrated in this JS fiddle (not mine, pulled from this thread ) 我描述的行为在此JS小提琴中进行了说明 (不是我的,从此线程中拉出)
My JS: 我的JS:
$(document).ready(function() {
$(window).on('load', function(){
var search_input = $("#listing-search-bar")
if (search_input) {
search_input.keyup(function(el){
autocomplete(el);
});
};
function autocomplete(el) {
var input = el.target;
var min_chars = 0;
if (input.value.length > min_chars) {
$.ajax({
type: 'GET',
url: "/listings/search",
data: {"query" : input.value},
dataType: "json"
}).done(function(response) {
// Add catch for if request failed
response.forEach( function(city) {
console.log(city)
if (!$(`#cities option[value="${city}"]`).length) {
$("#cities").append(`<option value="${city}"></option>`);
};
});
});
};
};
});
});
HTML: HTML:
<%= form_with url: search_listings_path, method: :get, local: true, id: "listing-search-bar" do |f| %>
<%= f.text_field :query, placeholder: "Search a city...", list: "cities" %>
<datalist id="cities"></datalist>
<% end %>
datalist options have some attribute like value, if you set value then it will open the drop-down with space. 数据列表选项具有一些属性,如value,如果您设置value,它将打开带空格的下拉列表。 For example you can check following code 例如,您可以检查以下代码
let originalInput = $("#input").val();
$("#datalist").append(`<option value=${originalInput}>${originalInput}</option>`);
$("#datalist-input").change(function(){
if(datalistText !== originalInput){
alert(`The original value: "${originalInput}" is not equal to: "${datalistText}"`);
}else{
alert(`The original value: "${originalInput}" is equal to: "${datalistText}"`);
}}); // end change
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.