Html 设置隐藏的数据列表选项值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39086427/
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-29 13:43:55  来源:igfitidea点击:

Setting hidden datalist option values

htmlhtml-selecthtml-datalist

提问by Rick Viscomi

In the snippet below, I have two methods to choose an item: input with datalist and traditional select with options.

在下面的代码片段中,我有两种选择项目的方法:使用数据列表输入和使用选项进行传统选择。

The select element keeps the option values hidden, and we're still able to get it with this.value. However, with the datalist, the value is actually displayed and the text content of the option is displayed as a secondary label.

select 元素隐藏选项值,我们仍然可以使用this.value. 但是,使用 datalist 时,实际显示的是值,选项的文本内容显示为辅助标签。

What I'd like is to have the input+datalist approach behave like a traditional select, where "Foo" and "Bar" are shown as options that when selected have values of "1" and "2" respectively.

我想要的是输入+ Datalist方法表现得像传统的选择,其中“foo”和“栏”显示为选定时选择有“1”和“2”的值。

I've also added a repeated name "Foo" with value "3". This is to show that any solution must not depend on unique options.

我还添加了一个重复的名称“Foo”,值为“3”。这是为了表明任何解决方案都不能依赖于独特的选项。

<input list="options" onchange="console.log(this.value)"/>
<datalist id="options">
  <option value="1">Foo</option>
  <option value="2">Bar</option>
  <option value="3">Foo</option>
</datalist>

<select onchange="console.log(this.value)">
  <option value=""></option>
  <option value="1">Foo</option>
  <option value="2">Bar</option>
  <option value="3">Foo</option>
</select>

回答by Oriol

There is no native way. For text inputs

没有本地方式。对于文本输入

The inputelement representsa one line plain text edit control for the element's value.

input元素代表了该元素的一个行纯文本编辑控件的值

So it's not possible to make a text input display some text different than its value.

所以不可能让文本输入显示一些与其值不同的文本。

You could hiHyman the valuegetter in HTMLInputElement.prototype, but I don't recommend it, and I don't see any way to know which option was chosen if the values are not unique.

您可以劫持 中的valuegetter HTMLInputElement.prototype,但我不推荐这样做,而且如果值不唯一,我看不出有任何方法可以知道选择了哪个选项。

var des = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value');
Object.defineProperty(HTMLInputElement.prototype, 'value', { get: function() {
  if(this.type === 'text' && this.list) {
    var value = des.get.call(this);
    var opt = [].find.call(this.list.options, function(option) {
      return option.value === value;
    });
    return opt ? opt.dataset.value : value;
  }
}});
<input list="options" oninput="console.log(this.value);" />
<datalist id="options">
  <option data-value="1">Foo</option>
  <option data-value="2">Bar</option>
  <option data-value="3">Foo</option>
</datalist>

Or maybe you can let the input show the value of the option instead of the text, but replace it immediately:

或者你可以让输入显示选项的值而不是文本,但立即替换它:

var inp = document.querySelector('input');
inp.addEventListener('input', function() {
  var value = this.value;
  var opt = [].find.call(this.list.options, function(option) {
    return option.value === value;
  });
  if(opt) {
    this.value = opt.textContent;
  }
});
<input list="options" oninput="console.log(this.value);" />
<datalist id="options">
  <option value="1">Foo</option>
  <option value="2">Bar</option>
  <option value="3">Foo</option>
</datalist>

In the second example, oninput="console.log(this.value)"shows the value of the option because that code runs before replacing the value to the text content. If you want later .valueaccessions to return the option value, you will need to hiHyman the valuegetter like in the first example.

在第二个示例中,oninput="console.log(this.value)"显示选项的值,因为该代码在将值替换为文本内容之前运行。如果您希望以后的.value访问返回选项值,则需要value像第一个示例中那样劫持getter。

回答by HybrisHelp

You can use data-valueand jqueryto make your value hidden.

您可以使用data-valuejquery来隐藏您的价值。

e.g:

例如:

$(document).ready(function() {

    $('#submit').click(function()
    {
        var value = $('#selected').val();
        alert($('#browsers [value="' + value + '"]').data('value'));
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="selected" list="browsers" name="browser">
<datalist id="browsers">
    <option data-value="1" value="InternetExplorer"></option>
    <option data-value="2" value="Firefox"></option>
    <option data-value="3" value="Chrome"></option>

</datalist>
<input id="submit" type="submit">

jsfiddle

提琴手

Thanks to @guest271314

感谢@guest271314

回答by RoboticRenaissance

So for the codebase I'm working on, I have a programatic fieldWriter for writing dynamic forms. I was asked to turn a bunch of selects into autocomplete datalists. What I did for this is set up 3 elements.

因此,对于我正在处理的代码库,我有一个用于编写动态表单的程序化 fieldWriter。我被要求将一堆选择转换为自动完成数据列表。我为此所做的是设置了 3 个元素。

  • One datalist with the name "somefield_dl"
  • One visible input with the name "somefield_proxy"
  • One hidden input with the name "somefield"
  • 一个名为“somefield_dl”的数据列表
  • 一个名为“somefield_proxy”的可见输入
  • 一个名为“somefield”的隐藏输入

On the datalists, I set each option like <option data-value="439" value="Readable Text"></option>

在数据列表上,我将每个选项设置为 <option data-value="439" value="Readable Text"></option>

With event handlers, anytime the "somefield_proxy" changes, the "somefield" is changed to the data-value of the option from "somefield_dl" with a matching value.

使用事件处理程序,只要“somefield_proxy”发生变化,“somefield”就会更改为具有匹配值的“somefield_dl”选项的数据值。

Code-wise, for using these, the main difference is that every time you update the field's value, you have to trigger the click event on the hidden input to update the proxy input. Also, when gathering data, you have to exclude the elements whose name ends with _proxy.

代码方面,对于使用这些,主要区别在于每次更新字段的值时,您必须触发隐藏输入上的点击事件以更新代理输入。此外,在收集数据时,您必须排除名称以 _proxy 结尾的元素。

回答by Stoycho Trenchev

The correct syntax of datalist is like bellow. Also there is no point to have two options with the same name. I took the JavaScript out of the HTML as it should be. ID attribute of the individual options can be replaced with other attribute.

datalist 的正确语法如下所示。同样,有两个名称相同的选项也没有意义。我从 HTML 中删除了 JavaScript,因为它应该是。单个选项的 ID 属性可以替换为其他属性。

$(function() {
  $('input[name=chooseOption]').on('input',function() {
    var selectedOption = $('option[value="'+$(this).val()+'"]');
    console.log(selectedOption.length ? selectedOption.attr('id') : 'This opiton is not in the list!');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input list="options" name="chooseOption">
<datalist id="options">
  <option id="1" value="Foo">
  <option id="2" value="Bar">
  <option id="3" value="Foo">
</datalist>

回答by Sun_Sparxz

Do not know this will help you, just made a try

不知道这对你有帮助,只是试了一下

  <input list="options" id="opt" oninput="onInput()">
  <datalist id="options">
        <option value="1">Foo</option>
       <option value="2">Bar</option>
       <option value="3">Foo</option> 
        <option value="4">Foo</option>
       <option value="5">Bar</option>
       <option value="6">Foo</option> 
  </datalist>




 $( document ).ready(function() {              
         var x =  document.getElementById("options");
           for (i = 0; i < x.length; i++)
            alert(x.options[i].value);     


            $("#opt").click(function(){
                 $("#opt").val("");});                   
             });

     function onInput() {
            var val = document.getElementById("opt").value;
            var opts = document.getElementById('options').childNodes;
             for (var i = 0; i < opts.length; i++) {
                    if (opts[i].value === val) {                
                    document.getElementById("opt").value = opts[i].value + "   "+ opts[i].innerHTML;
                    break;
                  }
                }
              }