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