How to display only the text in datalist HTML5 and not the value?
Asked Answered
C

3

35

Here is an example:

<input list="browsers" name="browser">
<datalist id="browsers">
    <option value="Internet Explorer">1</option>
    <option value="Firefox">2</option>
    <option value="Chrome">3</option>
    <option value="Opera">4</option>
    <option value="Safari">5</option>
</datalist>

http://jsfiddle.net/j7ehtqjd/1/

What I want to achieve is when I click on the input element the value would not be displayed, but ONLY the text (i.e. 1, 2, 3, 4, 5). I.e. the value should be hidden like it is with a general dropdown (<select> element).

This autocomplete feature is necessary, else I would have gone with the normal dropdown.

Characteristically answered 2/9, 2014 at 5:46 Comment(10)
You can move value to another parameter (for example, data-value) and set 1,2,3,4,5 as value.Holter
But i need to send the value to the back end using jquery.Characteristically
You can send data-value instead of valueHolter
And i just noticed the value is not readCharacteristically
And can u tell me how to send data-value, i use - $("#browsers").val()Characteristically
check this fiddle, yours, but Altered it http://jsfiddle.net/Lfgknh78/Khan
U have removed the text completely and the tyoe of text is showing as an errorCharacteristically
@Characteristically Take a look at updated fiddle.Holter
last fiddle jsfiddle.net/yy7j0xLyKhan
@Khan - I got to display the ctext in the dropdown. Not the value.Characteristically
E
31

Edit, updated

Following Regent

Try (v3)

html

<input id="selected" list="browsers" name="browser">
<datalist id="browsers">
    <option data-value="InternetExplorer" value="1"></option>
    <option data-value="Firefox" value="2"></option>
    <option data-value="Chrome" value="3"></option>
    <option data-value="Opera" value="4"></option>
    <option data-value="Safari" value="5"></option>
</datalist>
<input id="submit" type="submit">

js

$(document).ready(function() {

var data = {}; 
$("#browsers option").each(function(i,el) {  
   data[$(el).data("value")] = $(el).val();
});
// `data` : object of `data-value` : `value`
console.log(data, $("#browsers option").val());


    $('#submit').click(function()
    {
        var value = $('#selected').val();
        alert($('#browsers [value="' + value + '"]').data('value'));
    });
});

jsfiddle http://jsfiddle.net/guest271314/j7ehtqjd/13/

Epinephrine answered 2/9, 2014 at 6:18 Comment(6)
How to retrieve value and send earlier i used to type $("#browsers").val().Characteristically
@Characteristically Well, maybe fiddle from my question's comment should be added to answer for its completenessHolter
Ok i will try i am not getting itCharacteristically
is it possible not to mention the data-value and it takes it dynamically as we choose ?Characteristically
@Characteristically what do you mean? We take data-value dynamically based on value we have chosen. @guest271314, I hope answer is now sufficient for OP. At least I voted up.Holter
the "$('#browsers [value="' + value + '"]').data('value')"-part did the whole trick for my problem :)Carricarriage
D
4

A quite messy method for doing this without dependencies like jQuery (edit: I realise that jQuery is being used by the OP, but this method will integrate fine with or without jQuery, so might helps others who are not).

First, swap your value and text nodes around, like so:

<input list="browsers" name="browser" id="my_input">
  <datalist id="browsers">
    <option value="Internet Explorer">1</option>
    <option value="Firefox">2</option>
    <option value="Chrome">3</option>
    <option value="Opera">4</option>
    <option value="Safari">5</option>
  </datalist>
  <input type="submit">

This ensures that the input always shows the correct value for the user. Then add in some JavaScript to check the text node of the corresponding value, like so:

let $input = document.getElementById('my_input');
let $datalist = document.getElementById('browsers');

$input.addEventListener('change', () => {
  let _value = null;

  let input_value = $input.value;
  let options = $datalist.children;
  let i = options.length;

  while(i--) {
    let option = options[i];

    if(option.value == input_value) {
      _value = option.textContent;
      break;
    }
  }

  if(_value == null) {
    console.warn('Value does not exist');
    return false;
  }

  console.log('The value is:', _value );
});

You can also change the 'change' event listener to 'keyup' too, to get real-time feedback. And instead of console.log('The value is:', _value ) you can simply add in an additional hidden input to store the value, thus allowing you to send both the value and id.

This uses modern JavaScript notation, but to make it backward compatible just need to change the 'change', () => { call to 'change', function() { and change let to var.

Updated: using ES6

A slightly more up-to-date answer than above

const input = document.getElementById('my_input');
const list = document.getElementById('browsers');

input.addEventListener('change', () => {
  const {value: inputVal} = input
  const children = Array.from(list.children)

  // Fetch matched elem
  const [matchedElem] = children.filter(({value}) => value === inputVal)
  
  // If element doesn't exist, no matches
  if(!matchedElem) {
    console.log('No matches found')
    
    return
  }
  
  // Do whatever
  console.log('Matched value for', matchedElem.value, 'is', matchedElem.textContent)
});
<input type="search" list="browsers" name="browser" id="my_input">

<datalist id="browsers">
  <option value="Internet Explorer">1</option>
  <option value="Firefox">2</option>
  <option value="Chrome">3</option>
  <option value="Opera">4</option>
  <option value="Safari">5</option>
</datalist>

<input type="submit">
Delrosario answered 24/5, 2018 at 16:15 Comment(0)
S
1

I though I would add a shorter Vanilla JS version of these answers. This will hide the true value, but when the item is submitted, it will replace it with your desired value on the form.

<input id="selected" list="browsers" name="browser" >
<datalist id="browsers">
    <option data-value="InternetExplorer" value="1"></option>
    <option data-value="Firefox" value="2"></option>
    <option data-value="Chrome" value="3"></option>
    <option data-value="Opera" value="4"></option>
    <option data-value="Safari" value="5"></option>
</datalist>
<input id="submit" type="submit">```

<script>
function getRealValue(ele){
  var dl=ele.list.options;
  for (var x=0;x<dl.length;x++){
    if (dl[x].value==ele.value){
      ele.value=dl[x].dataset.value;
      return dl[x].dataset.value;
    }
  }
}
</script>

Sestina answered 1/5, 2020 at 13:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.