基于datalist实现自动补全:显示及选值问题求助
Hey there! Let's fix up your datalist issues step by step. I'll go through both your questions and adjust your code to make it work exactly as you want.
Problem 1: Make datalist only display the value
Right now, you’ve got the option’s val() and html() reversed for your goal. The text inside the <option> element is what shows up in the dropdown, while the val attribute determines what gets populated into the input when an option is selected.
To only show the value (your el[1]) in the dropdown, we’ll set the option’s visible text to el[1], and store the corresponding key (el[0]) in a custom data-* attribute (like data-key) so we can grab it later when needed.
Problem 2: Get both the selected key and value
Listening for clicks on the datalist itself isn’t reliable—instead, we should listen for input or change events on the text input element. When the user selects an option (or types a matching value), we can find the corresponding option in the datalist, then pull the key from its data-key attribute and the value from its value/text.
Modified Full Code
<input type="text" id="tex_in" list="dataList" /> <datalist id="dataList"></datalist> <script> // Initialize or reset the auto-completion array let autoCan = []; // Replace these with your actual values const proxy = "/your-proxy-endpoint"; const table = "your-target-table"; // Assume query comes from the input's value (adjust as needed) const query = $("#tex_in").val(); if (query.length >= 4) { // Clear existing options and reset the array before fetching new data autoCan = []; $("#dataList").empty(); $.ajax({ type: "POST", url: proxy, data: JSON.stringify({ table: table, query: query }), dataType: "json", contentType: "application/json", success: function (response) { // jQuery already parses JSON responses, no need to stringify/parse again response.response.docs.forEach(function (el) { if (autoCan.length < 10) { autoCan.push([el["key"], el["value"]]); } }); if (autoCan.length) { autoCan.forEach(function (el) { // Build option: show value in dropdown, store key in data attribute const option = $("<option></option>") .text(el[1]) // Visible text in the dropdown .val(el[1]) // Value that populates the input .data("key", el[0]); // Store the associated key for later $("#dataList").append(option); }); } }, error: function () { console.log("error at server"); }, }); } else { // Clear the datalist when the query is too short $("#dataList").empty(); } // Capture selection or input changes to get key and value $("#tex_in").on("input change", function () { const inputValue = $(this).val(); // Find the option that matches the input's current value const selectedOption = $("#dataList option").filter(function () { return $(this).val() === inputValue; }); if (selectedOption.length) { const selectedKey = selectedOption.data("key"); const selectedValue = selectedOption.val(); console.log("Selected Key:", selectedKey); console.log("Selected Value:", selectedValue); // If you want to display these values on the page, add elements and update them here // Example: // $("#key-display").text(`Key: ${selectedKey}`); // $("#value-display").text(`Value: ${selectedValue}`); } }); </script>
Key Changes Explained:
- State reset: We clear the
autoCanarray and empty the datalist before each AJAX call to avoid duplicate options piling up. - Option structure: We use
text(el[1])to show only the value in the dropdown, anddata('key', el[0])to secretly store the associated key. - Reliable event handling: We listen to the input’s
inputandchangeevents instead of the datalist’s click—this works even when users type to match an option instead of clicking it. - Simplified response handling: You don’t need to stringify and re-parse the
response—jQuery automatically parses JSON whendataType: "json"is set.
内容的提问来源于stack exchange,提问作者gaurav1207

