Get the data-id of the selected option in a datalist
Asked Answered
K

5

9

Ok, I have the following HTML source:

<form method="post" action="/" id="search">
  <input list="animals" name="animal">
    <datalist id="animals">
      <option label="Alaskan Malamute" data-id="d8c" value="Dog">
      <option label="Siberian Husky" data-id="w30" value="Dog">
      <option label="Aegean" data-id="rxx" value="Cat">
    </datalist>
</form>

And the JS

function doKeyUp(e) {
  if (e.preventDefault) e.preventDefault();

  if(e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40 ) {return;}

  var input = document.getElementById("animal");
  var search_after = input.value.trim();
  var form = document.getElementsByTagName("form")[0];

  var datalist = document.getElementsByTagName('datalist')[0];

  if (search_after.length >= 2) {

    if (e.keyCode == 13 && search_after.length >= 3) {
      var id = "value of data-id";
      // How to obtain and submit the `data-id` of the selected option.
      document.getElementById("search").submit();
    }
  }
}  // dokeyup



document.addEventListener("DOMContentLoaded", function(event) {
  document.getElementById("search").onsubmit = function (e) {
    console.log("SUBMIT");
    return false;
  };

  document.addEventListener( "keyup", doKeyUp, true);
});

When the user then selects an option, how do I get the data-id of the selected <option> - which is the actual data I want to submit and process on the server side.

This is a project where I'm trying to write everything by my self, no jQuery this time.

Know I can do console.log(datalist.options[1]);, but can not figure how I obtain the selected index.

Update March 4: Must ask again, no one who has any tips for me ?

Still not figured this out, and have really run out of ideas... The last I've tried stopped at, before the form submission:

for (var i=0; i<document.getElementById('animals').options.length; i++) {
    if (document.getElementById('animals').options[i].value == document.getElementsByName("animal")[0].value) {
        var id = document.getElementById('animals').options[i].getAttribute('data-id');
        break;
    }
}

Is it in any way possible to get the selected index of the chosen option - or am I still on the wrong path ? This above stops at the first element, anyway.

Kiloliter answered 5/2, 2017 at 13:39 Comment(4)
You can easily get it done by jqueryOverturf
Thanks, but as mentioned I'll try to make it without any framework / jQuery.Kiloliter
Ok, @KaushikThanki, do you have any pointers on how to do this with jQuery ? Still haven't figured this out. Have been reading and searching all over, none of the things I have tried out fixes my problem.Kiloliter
This is the exact same way I was able to do it. Even looking at the attributes of the values themselves, all of their indexes result in 0, so not sure if it is doable any other way with javascript than the way you have done it.Schauer
O
15

Check this answer as jquery solution .. & sorry for late reply .

$(function(){
    $('#p').click(function(){
        console.log($("#animals option[value='" + $('#someid').val() + "']").attr('data-id'));
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="/" id="search">
  <input list="animals" name="animal" id="someid">
    <datalist id="animals">
      <option label="Alaskan Malamute" data-id="d8c" value="Dog">
      <option label="Siberian Husky" data-id="w30" value="Dog">
      <option label="Aegean" data-id="rxx" value="Cat">
    </datalist>
    <span id="p">Click</span>
</form>
Overturf answered 15/2, 2017 at 10:50 Comment(0)
T
1

the value of the data-id attribute of the selected < option > in a datalist can be accessed from the DOM datalist object, like this

<input list="animals" id="input-animal" name="animal">
<datalist id="animals">
  <option label="Alaskan Malamute" data-id="d8c" value="Dog">
  <option label="Siberian Husky" data-id="w30" value="Dog">
  <option label="Aegean" data-id="rxx" value="Cat">
</datalist>

 animals.options.namedItem( input-animal.value ).getAttribute('data-id')

namedItem() is a method which returns the element from the collection with the specified id.

Tetrastich answered 21/4, 2020 at 22:34 Comment(0)
B
1

Russel Newton's solution using namedItem almost worked for me. Here is an adjusted solution that worked, using the name attribute on the option tags. (Reference: https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/namedItem)

var form = document.getElementById('dataForm');
form.addEventListener('submit', validateform);

function validateform() {
  event.preventDefault();
  var selectedOption = dataListId.options.namedItem(inputId.value);
  if (selectedOption) {
      var selectedId = selectedOption.getAttribute('data-id');
      var result = "Country ID: " + selectedId;
      console.log({selectedId});
  } else {
      var result = "No ID available for value: " + inputId.value;
  }
  document.getElementById('resultID').textContent = result; 
  
  // Can also use : 
  // inputElement = document.getElementById("inputId");
  // listElement = document.getElementById("dataListId");
}
div.resultID {
  color: #85144b;
  font-weight: bold;
  margin-top: 30px;
  margin-left: 20px;
}
<form id="dataForm">
  <input id="inputId" list="dataListId" value="" placeholder="Choose a country">
  <datalist id="dataListId">
            <option data-id="1" name="Country A">Country A</option>
            <option data-id="36" name="Country B">Country B</option>
            <option data-id="59" name="Country C">Country C</option>
        </datalist>
  <button id="submitButton" type="submit">Submit</button>
  <div id="resultID" class="resultID"></div>
</form>
Basilbasilar answered 4/2, 2021 at 13:48 Comment(0)
E
0

https://kodingkantor.blogspot.co.id/2018/03/get-data-id-in-datalist-option.html

console.log($("#locations option[value='" + $('#location1').val() + "']").attr('data-id'));
Erdei answered 26/3, 2018 at 7:31 Comment(0)
S
0

Without jQuery!

When input value has changed, data attributes of input field get merged:

document.querySelector('#animal').addEventListener('input', (e) => {
  Object.assign(e.target.dataset, document.querySelector('#' + e.target.getAttribute('list') + ' option[value="' + e.target.value + '"]').dataset);
  console.log('dataset of input changed: ', e.target.dataset)
});
<input list="animals" id="animal" data-id="xxx">
<datalist id="animals">
  <option value="Alaskan Malamute"  data-id="123" data-alpha="abc">
  <option value="Siberian Husky"    data-id="456" data-alpha="def">
  <option value="Aegean"            data-id="789" data-alpha="ghi">
</datalist>
Stipend answered 6/11, 2020 at 14:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.