Oliver Kucharzewski
Oliver Kucharzewski

Reputation: 2645

How to pass the id attribute instead of the value

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)

Upvotes: 0

Views: 488

Answers (4)

I&#39;m Geeker
I&#39;m Geeker

Reputation: 4637

You just use attr event

$('#to').on('input', function() {
  $(this).val($(this).next().find('option[value="' + this.value + '"]').attr('id'))
})

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

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>

Upvotes: 2

Justinas
Justinas

Reputation: 43479

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.

Upvotes: 0

Arun Babu
Arun Babu

Reputation: 118

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/>

Upvotes: 0

Related Questions