Javascript 显示数据列表标签但提交实际值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29882361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:13:05  来源:igfitidea点击:

Show datalist labels but submit the actual value

javascripthtmlcross-browserhtml-datalist

提问by Stephan Muller

Currently the HTML5 <datalist>element is supported in most major browsers (except Safari) and seems like an interesting way to add suggestions to an input.

目前<datalist>,大多数主流浏览器(Safari 除外)都支持HTML5元素,这似乎是一种向输入添加建议的有趣方式。

However, there seem to be some discrepancies between the implementation of the valueattribute and the inner text on the <option>. For example:

但是,value属性的实现与<option>. 例如:

<input list="answers" name="answer">
<datalist id="answers">
  <option value="42">The answer</option>
</datalist>

This is handled differently by different browsers:

不同的浏览器对此有不同的处理:

Chrome and Opera:
Datalist in Chrome/Opera

铬和歌剧:
Chrome/Opera 中的数据列表

FireFox and IE 11:
Datalist in FireFox

火狐和 IE 11:
FireFox 中的数据列表

After selecting one, the input is filled with the value and not the inner text. I only want the user to see the text ("The answer") in the dropdown and in the input, but pass the value 42on submit, like a selectwould.

选择一个后,输入将填充值而不是内部文本。我只希望用户在下拉列表和输入中看到文本(“答案”),但42在提交时传递值,就像select会一样。

How can I make all browsers have the dropdown list show the labels (inner text) of the <option>s, but send the valueattribute when the form is submitted?

如何让所有浏览器让下拉列表显示<option>s的标签(内部文本),但在value提交表单时发送属性?

回答by Stephan Muller

Note that datalistis not the same as a select. It allows users to enter a custom value that is not in the list, and it would be impossible to fetch an alternate value for such input without defining it first.

请注意,datalist这与select. 它允许用户输入不在列表中的自定义值,如果不先定义它,就不可能为此类输入获取替代值。

Possible ways to handle user input are to submit the entered value as is, submit a blank value, or prevent submitting. This answer handles only the first two options.

处理用户输入的可能方法是按原样提交输入的值、提交空白值或阻止提交。此答案仅处理前两个选项。

If you want to disallow user input entirely, maybe selectwould be a better choice.

如果您想完全禁止用户输入,也许select是更好的选择。



To show only the text value of the optionin the dropdown, we use the inner text for it and leave out the valueattribute. The actual value that we want to send along is stored in a custom data-valueattribute:

为了option在下拉列表中仅显示 的文本值,我们对其使用内部文本并省略该value属性。我们要发送的实际值存储在自定义data-value属性中:

To submit this data-valuewe have to use an <input type="hidden">. In this case we leave out the name="answer"on the regular input and move it to the hidden copy.

要提交此文件,data-value我们必须使用<input type="hidden">. 在这种情况下,我们将name="answer"常规输入上的 去掉 并将其移动到隐藏副本。

<input list="suggestionList" id="answerInput">
<datalist id="suggestionList">
    <option data-value="42">The answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">

This way, when the text in the original input changes we can use javascript to check if the text also present in the datalistand fetch its data-value. That value is inserted into the hidden input and submitted.

这样一来,当原始输入文本的变化,我们可以使用JavaScript来检查,如果文本也存在于datalist和获取其data-value。该值被插入到隐藏的输入中并提交。

document.querySelector('input[list]').addEventListener('input', function(e) {
    var input = e.target,
        list = input.getAttribute('list'),
        options = document.querySelectorAll('#' + list + ' option'),
        hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden'),
        inputValue = input.value;

    hiddenInput.value = inputValue;

    for(var i = 0; i < options.length; i++) {
        var option = options[i];

        if(option.innerText === inputValue) {
            hiddenInput.value = option.getAttribute('data-value');
            break;
        }
    }
});


The id answerand answer-hiddenon the regular and hidden input are needed for the script to know which input belongs to which hidden version. This way it's possible to have multiple inputs on the same page with one or more datalists providing suggestions.

脚本需要idansweranswer-hiddenon 常规和隐藏输入才能知道哪个输入属于哪个隐藏版本。这样就可以input在同一页面上有多个s,其中一个或多个datalists 提供建议。

Any user input is submitted as is. To submit an empty value when the user input is not present in the datalist, change hiddenInput.value = labelto hiddenInput.value = ""

任何用户输入都按原样提交。要在数据列表中不存在用户输入时提交空值,请更改hiddenInput.value = labelhiddenInput.value = ""



Working jsFiddle examples: plain javascriptand jQuery

工作 jsFiddle 示例:纯 javascriptjQuery

回答by Hezbullah Shah

The solution I use is the following:

我使用的解决方案如下:

<input list="answers" id="answer">
<datalist id="answers">
  <option data-value="42" value="The answer">
</datalist>

Then access the value to be sent to the server using JavaScript like this:

然后使用 JavaScript 访问要发送到服务器的值,如下所示:

var shownVal = document.getElementById("answer").value;
var value2send = document.querySelector("#answers option[value='"+shownVal+"']").dataset.value;


Hope it helps.


希望能帮助到你。

回答by Gal Albalak

When clicking on the button for search you can find it without a loop.
Just add to the option an attribute with the value you need (like id) and search for it specific.

单击搜索按钮时,您可以在没有循环的情况下找到它。
只需将具有您需要的值的属性(如id)添加到选项中,然后搜索它。

$('#search_wrapper button').on('click', function(){
console.log($('option[value="'+ 
$('#autocomplete_input').val() +'"]').data('value'));
})

回答by cobbystreet

I realize this may be a bit late, but I stumbled upon this and was wondering how to handle situations with multiple identical values, but different keys (as per bigbearzhu's comment).

我意识到这可能有点晚了,但我偶然发现了这一点,并想知道如何处理具有多个相同值但不同键的情况(根据 bigbearzhu 的评论)。

So I modified Stephan Muller's answer slightly:

所以我稍微修改了 Stephan Muller 的回答:

A datalist with non-unique values:

具有非唯一值的数据列表:

<input list="answers" name="answer" id="answerInput">
<datalist id="answers">
  <option value="42">The answer</option>
  <option value="43">The answer</option>
  <option value="44">Another Answer</option>
</datalist>
<input type="hidden" name="answer" id="answerInput-hidden">

When the user selects an option, the browser replaces input.valuewith the valueof the datalistoption instead of the innerText.

当用户选择一个选项,浏览器内容替换input.valuevalue所述的datalist选项而不是innerText

The following code then checks for an optionwith that value, pushes that into the hidden field and replaces the input.valuewith the innerText.

下面的代码然后检查一个optionwith that value,将其推入隐藏字段并替换input.valueinnerText

document.querySelector('#answerInput').addEventListener('input', function(e) {
    var input = e.target,   
        list = input.getAttribute('list'),
        options = document.querySelectorAll('#' + list + ' option[value="'+input.value+'"]'),
        hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden');

    if (options.length > 0) {
      hiddenInput.value = input.value;
      input.value = options[0].innerText;
      }

});

As a consequence the user sees whatever the option's innerTextsays, but the unique id from option.valueis available upon form submit. Demo jsFiddle

因此,用户会看到选项innerText所说的任何内容,但option.value表单提交时可以使用唯一的 id 。 演示 jsFiddle

回答by 23r0

Using PHP i've found a quite simple way to do this. Guys, Just Use something like this

使用 PHP 我找到了一种非常简单的方法来做到这一点。伙计们,就用这样的东西

<input list="customers" name="customer_id" required class="form-control" placeholder="Customer Name">
            <datalist id="customers">
                <?php 
    $querySnamex = "SELECT * FROM `customer` WHERE fname!='' AND lname!='' order by customer_id ASC";
    $resultSnamex = mysqli_query($con,$querySnamex) or die(mysql_error());

                while ($row_this = mysqli_fetch_array($resultSnamex)) {
                    echo '<option data-value="'.$row_this['customer_id'].'">'.$row_this['fname'].' '.$row_this['lname'].'</option>
                    <input type="hidden" name="customer_id_real" value="'.$row_this['customer_id'].'" id="answerInput-hidden">';
                }

                 ?>
            </datalist>

The Code Above lets the form carry the id of the option also selected.

上面的代码让表单携带也被选中的选项的 id。