Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 892
Jon Avatar asked Feb 05 '17 13:02

Jon


People also ask

How do I get the data ID of an element?

Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.

Is the Datalist tag and select Tag same?

Select input element presents options for the users from which they need to select one of them. On the otherhand, Datalist presents a list of suggested values to the associated input form (text) field and users are free to select one of those suggested values or type in their own value.


3 Answers

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>
like image 66
Kaushik Thanki Avatar answered Oct 16 '22 08:10

Kaushik Thanki


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.

like image 42
russell newton Avatar answered Oct 16 '22 10:10

russell newton


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>
like image 24
Jungle Editor Avatar answered Oct 16 '22 09:10

Jungle Editor