简体   繁体   中英

Get the data-id of the selected option in a datalist

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.

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>

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.

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>

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

console.log($("#locations option[value='" + $('#location1').val() + "']").attr('data-id'));

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM