Setting hidden datalist option values

前端 未结 5 701
旧巷少年郎
旧巷少年郎 2020-12-06 09:55

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 hidde

5条回答
  •  悲哀的现实
    2020-12-06 10:37

    There is no native way. For text inputs

    The input element represents a one line plain text edit control for the element's value.

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

    You could hijack the value getter 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.

    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;
      }
    }});
    
    
      
      
      
    

    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;
      }
    });
    
    
      
      
      
    

    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 .value accessions to return the option value, you will need to hijack the value getter like in the first example.

提交回复
热议问题