关闭自动建议框

huangapple go评论89阅读模式
英文:

Turning off the AutoSuggestion Box

问题

我正在使用第三方工具,根据客户的输入自动填充地址,所以如果客户输入"123 test Street",建议框会显示所有接近"123 test Street"的地址。我只想在客户输入的地址在建议框中不存在时关闭建议框,这样如果"123 test Street"在建议框中不存在,建议框应关闭并允许客户输入他们想要的地址。这是我拥有的HTML代码:

<div>
    <label>Address:</label>
    <div>
        <input type="text" id="address" value="" autocomplete="off" />
    </div>
    <div id="suggestionContainer">
        <div id="suggestionBox" class="inactive"></div>
    </div>
    <label>City:</label>
    <div><input type="text" id="city" value="" /></div>
    <label>State:</label>
    <div><input type="text" id="state" value="" /></div>
    <label>ZIP Code:</label>
    <div><input type="text" id="zipcode" value="" /></div>
</div>

我尝试在地址字段中添加autocomplete="off",但没有起作用。以下是我拥有的JavaScript代码:

const addressElement = document.getElementById("address");
const suggestionElement = document.getElementById("suggestionBox");

addressElement.addEventListener("keyup", (e) => {
    const searchValue = e.target.value;
    suggestionElement.innerHTML = "";
    if (!searchValue) {
        suggestionElement.classList.remove("active");
        suggestionElement.classList.add("inactive");
        return;
    }

    suggestionElement.classList.remove("inactive");
    suggestionElement.classList.add("active");

    sendLookupRequest(searchValue);
});

这是formatSuggestions的JavaScript代码:

const formatSuggestions = (suggestions) => {
    const formattedSuggestions = suggestions.map((suggestion) => {
        const divElement = document.createElement("div");
        const {
            street_line,
            city,
            state,
            zipcode,
            secondary,
            entries
        } = suggestion;
        const hasSecondaryData = secondary && entries > 1;

        divElement.innerText = `${street_line} ${secondary} ${hasSecondaryData ? `(${entries} entries)` : ""} ${city} ${state} ${zipcode}`;

        divElement.addEventListener("click", async () => {
            const streetLineWithSecondary = `${street_line} ${secondary}`.trim();
            if (hasSecondaryData) {
                suggestionElement.innerHTML = "";
                const selected = `${streetLineWithSecondary} (${entries}) ${city} ${state} ${zipcode}`;
                await sendLookupRequest(streetLineWithSecondary, selected);
            } else {
                suggestionElement.classList.remove("active");
                suggestionElement.classList.add("inactive");
            }
            populateForm({ streetLineWithSecondary, city, state, zipcode });
        });

        return divElement;
    });

    suggestionElement.append(...formattedSuggestions);
};

根据你的描述,即使地址在数据库中不存在,上面的JavaScript代码会继续显示自动建议框。如果你想在地址不存在时关闭建议框,你可以在formatSuggestions函数中添加一些逻辑来处理这种情况。如果没有建议,你可以将建议框设为不活跃状态:

const formatSuggestions = (suggestions) => {
    const formattedSuggestions = suggestions.map((suggestion) => {
        // ... 其余代码 ...

        divElement.addEventListener("click", async () => {
            // ... 其余代码 ...
        });

        return divElement;
    });

    if (formattedSuggestions.length === 0) {
        suggestionElement.classList.remove("active");
        suggestionElement.classList.add("inactive");
    } else {
        suggestionElement.classList.remove("inactive");
        suggestionElement.classList.add("active");
    }

    suggestionElement.append(...formattedSuggestions);
};

这将在没有建议时关闭建议框。希望这对你有所帮助。如果有其他问题,请随时提问。

英文:

I am using a third party tool that Auto populates the address based on whatever the customer is typing so if the customer is Typing "123 test Street", the suggestion box will show all the addresses that are close to "123 test Street". I just want the suggestion box to close if the address that a customer typed does not exists in the suggestion box so if "123 test Street" does not exits in the suggestion box then the suggestion box should close and let the customer type the address that they want. This is the HTML, I have:

&lt;div&gt;
             &lt;label&gt;Address:&lt;/label&gt;
      &lt;div&gt;
        &lt;input type=&quot;text&quot; id=&quot;address&quot; value=&quot;&quot; autocomplete=&quot;off&quot; /&gt;
      &lt;/div&gt;
      &lt;div id=&quot;suggestionContainer&quot;&gt;
        &lt;div id=&quot;suggestionBox&quot; class=&quot;inactive&quot;&gt;&lt;/div&gt;
      &lt;/div&gt;
      &lt;label&gt;City:&lt;/label&gt;
      &lt;div&gt;&lt;input type=&quot;text&quot; id=&quot;city&quot; value=&quot;&quot; /&gt;&lt;/div&gt;
      &lt;label&gt;State:&lt;/label&gt;
      &lt;div&gt;&lt;input type=&quot;text&quot; id=&quot;state&quot; value=&quot;&quot; /&gt;&lt;/div&gt;
      &lt;label&gt;ZIP Code:&lt;/label&gt;
      &lt;div&gt;&lt;input type=&quot;text&quot; id=&quot;zipcode&quot; value=&quot;&quot; /&gt;&lt;/div&gt;
        &lt;/div&gt;

I tried putting autocomplete="off" in the address field, but that did not work. Below is the Javascript that I have:

const addressElement = document.getElementById(&quot;address&quot;);
const suggestionElement = document.getElementById(&quot;suggestionBox&quot;);

addressElement.addEventListener(&quot;keyup&quot;, (e) =&gt; {
 
    const searchValue = e.target.value;
    suggestionElement.innerHTML = &quot;&quot;;
    if (!searchValue) {
        suggestionElement.classList.remove(&quot;active&quot;);
        suggestionElement.classList.add(&quot;inactive&quot;);
        return;
    }

    suggestionElement.classList.remove(&quot;inactive&quot;);
    suggestionElement.classList.add(&quot;active&quot;);

    sendLookupRequest(searchValue);
});
 const request = await fetch(
         `https://us-autocomplete-pro.api.smarty.com/lookup?${params}`
    );
    const data = await request.json();

    if (data?.suggestions?.length &gt; 0) formatSuggestions(data.suggestions);
};

This is the Javascript for formatSuggestions:

const formatSuggestions = (suggestions) =&gt; {
    const formattedSuggestions = suggestions.map((suggestion) =&gt; {
        const divElement = document.createElement(&quot;div&quot;);
        const {
            street_line,
            city,
            state,
            zipcode,
            secondary,
            entries
        } = suggestion;
        const hasSecondaryData = secondary &amp;&amp; entries &gt; 1;

        divElement.innerText = `${street_line} ${secondary} ${hasSecondaryData ? `(${entries} entries)` : &quot;&quot;
            } ${city} ${state} ${zipcode}`;

        divElement.addEventListener(&quot;click&quot;, async () =&gt; {
            const streetLineWithSecondary = `${street_line} ${secondary}`.trim();
            if (hasSecondaryData) {
                suggestionElement.innerHTML = &quot;&quot;;
                const selected = `${streetLineWithSecondary} (${entries}) ${city} ${state} ${zipcode}`;
                await sendLookupRequest(streetLineWithSecondary, selected);
            } else {
                suggestionElement.classList.remove(&quot;active&quot;);
                suggestionElement.classList.add(&quot;inactive&quot;);
            }
            populateForm({ streetLineWithSecondary, city, state, zipcode });
        });

        return divElement;
    });

    suggestionElement.append(...formattedSuggestions);
};

I am very new in Javascript. Any help with this will be highly appreciated. With the above Javascript, the autosuggestion box keep showing up even if the address does not exist in the database. below is the screen shot:

关闭自动建议框

As you can see, above address shows a blank suggestion box and it does not go away even if that address does not exists.

答案1

得分: 1

你可以像这样修改你的 sendLookupRequest 函数:

const sendLookupRequest = async (searchValue, selected = "") => {
    const params = new URLSearchParams({
        key: smartyKey,
        search: searchValue,
        source: "all",
        selected
    });

    const request = await fetch(
        `https://us-autocomplete-pro.api.smarty.com/lookup?${params}`
    );

    const data = await request.json();

   // if (data?.suggestions?.length > 0) formatSuggestions(data.suggestions);

    if (data?.suggestions?.length > 0) {
        //建议存在。
        formatSuggestions(data.suggestions);

    } else {
        //建议不存在,隐藏自动完成框。
        suggestionElement.innerHTML = "";
        suggestionElement.classList.remove("active");
        suggestionElement.classList.add("inactive");
    };
};

这将在地址字段包含无效条目时隐藏建议框。

英文:

You can modify your sendLookupRequest like this:

const sendLookupRequest = async (searchValue, selected = &quot;&quot;) =&gt; {
    const params = new URLSearchParams({
        key: smartyKey,
        search: searchValue,
        source: &quot;all&quot;,
        selected
    });
  
    const request = await fetch(
        `https://us-autocomplete-pro.api.smarty.com/lookup?${params}`
    );
    
    const data = await request.json();

   // if (data?.suggestions?.length &gt; 0) formatSuggestions(data.suggestions);

    if (data?.suggestions?.length &gt; 0) {
        //Suggestion exists.
        formatSuggestions(data.suggestions);
     
    } else {
        //Suggestion does not exists hide autocomplete.
        suggestionElement.innerHTML = &quot;&quot;;
        suggestionElement.classList.remove(&quot;active&quot;);
        suggestionElement.classList.add(&quot;inactive&quot;);
    };



};

this will hide the suggestion box if the address field has invalid entry

答案2

得分: 1

谷歌浏览器中的自动完成功能越来越注重客户需求,而不是开发者友好。有很多方法可以避免这个功能,但它们可能只能在一段时间内生效,然后被谷歌开发者吸收。解决方案的关键在于使用自动完成内容来选择要显示的数据。这个解决方案相当难以禁用,可以使用文本而不是数字来改进。基本上,在自动完成属性中添加了一个随机字符串。我用PHP做了这个,因为它很方便,但可以用多种方式在JS中实现。以下是代码:

autocomplete=&quot;text&lt;?=rand()?&gt;&quot;

这样,谷歌浏览器会认真搜索某些内容,但找不到任何内容,返回一个空列表。

英文:

The autocomplete feature in Chrome has become more and more customer oriented rather than developer friendly.
There are many tricks on the net to avoid this feature but they work maybe for a while and then they get absorbed by Chrome developers.
The key to this solution is that the content of the autocomplete is used to select which data to show.

This solution is quite difficult to disable and it can be improved using text instead of numbers.
Basically a random string is added to a text in the autocomplete attribute.
I did it with PHP because it's handy, but it can be done in JS in many ways.
Here is the code:

autocomplete=&quot;text&lt;?=rand()?&gt;&quot;

This way Chrome looks diligently for something and doesn't find anything, returning an empty list.

huangapple
  • 本文由 发表于 2023年8月5日 06:58:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76839502.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定