Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to get the datalist option id and assign to the input data attributes

i don’t know how to write this code in jquery or javascript hoping that someone can help me to reach this logic.

my goal is when i select the datalist option i want to get the attribute ID of the selected option and make it to the value of data-set.

<input type="text" id="city" data-set="" list="citylist"  name="city" required>
<datalist id="citylist">
    <option class="citydata" id="012801000">Adams</option>
    <option class="citydata" id="012802000">Bacarra</option>
    <option class="citydata" id="012803000">Badoc</option>
</datalist>

example i select the Adams with the attribute of ID

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

then the output of the input now is

<input type="text" id="city" data-set="012801000" value="Adams" list="citylist"  name="city" required>

>Solution :

You can attach the input event to the element using addEventListener so that you can get and set the attribute property of the element.

You can try the following way:

const cityInput = document.getElementById('city');
const cityListOptions = document.querySelectorAll('#citylist > .citydata');

//attach the event
cityInput.addEventListener('input', function() {
  console.clear(); //clear the console
  //get the selected option
  const selectedOption = [...cityListOptions].find(option => option.value === cityInput.value);
  //check if selectedOption is truthy
  if (selectedOption) {
    //get and set the property
    cityInput.dataset.set = selectedOption.id;
    cityInput.setAttribute('value', selectedOption.value);
  }    
  console.log(document.getElementById('city')); //test
});
<input type="text" id="city" data-set="" list="citylist" name="city" required>
<datalist id="citylist">
  <option class="citydata" id="012801000">Adams</option>
  <option class="citydata" id="012802000">Bacarra</option>
  <option class="citydata" id="012803000">Badoc</option>
</datalist>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading