0

I'm quite new to the HTML5 datalists and I noticed that the value section is displayed in-conjunction to the text within the tag. but I didnt want the value inside the 'id' attribute to be displayed so I placed it into the 'id' tag instead as another storage method. As so:

   <td> 
    <input list="to" id="to-selected" style="width: 145px;">
    <datalist id="to"> 
    <option value="4000 Islands, Laos" id="4483"></option>
    </datalist>
   </td>

If this is possible, how would I retrieve the value of the id attribute? (I know how to post it if I get the value)

Oliver Kucharzewski
  • 2,523
  • 4
  • 27
  • 51
  • http://jsfiddle.net/arunpjohny/zsb4155d/2/ – Arun P Johny Mar 20 '15 at 06:41
  • possible duplicate of [Show datalist labels but submit the actual value](http://stackoverflow.com/questions/29882361/show-datalist-labels-but-submit-the-actual-value) – Stephan Muller Apr 30 '15 at 19:27
  • @StephanMuller This is not a dupe of that one. This is asking about how to retrieve the `id` contents, not how to submit the `value` contents. – TylerH May 01 '15 at 20:29
  • @TylerH Once again you're right. The answer is 99% the same, but the question is different. Vote retracted. – Stephan Muller May 01 '15 at 20:42

4 Answers4

2

One possible option is to use the input event and set the value manually

$('#to-selected').on('input', function() {
  $(this).val($(this).next().find('option[value="' + this.value + '"]').data('id'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input list="to" id="to-selected" style="width: 145px;" />
<datalist id="to">
  <option value="4000 Islands, Laos" data-id="4483"></option>
</datalist>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

If you don't want it to be displayed you can make it hidden and retrieve the value as usual

<input type=hidden id="something" value="4483"/>

or

<input type=text id="something" value="4483" hidden/>
Arun Babu
  • 108
  • 2
  • 13
0

To get any attribute using query, you use .attr('attributeName'):

$('datalist').attr('id');

If using data-* (like in <input data-id="5"/>) you can use

$('input').data('id');

Just keep in mind that if changing data-* value with js, no changes will be reflected to DOM element, only to data set in memory.

Justinas
  • 41,402
  • 5
  • 66
  • 96
0

You just use attr event

$('#to').on('input', function() {
  $(this).val($(this).next().find('option[value="' + this.value + '"]').attr('id'))
})
I'm Geeker
  • 4,601
  • 5
  • 22
  • 41