Get Predifined Text Option of Datalist or User Entered Text (not value)

36 Views Asked by At

I need to get the content (text, not value) of the datalist option selected by the user OR some other content written by the user even that content don't match with the content of any options.

And I want to put the content inside a variable.

Thanks.

<input type="text"  id="input-color" list="color" autocomplete="off" required >
<datalist id="color">
<option>WHITE</option>
<option>BLACK</option>
<option>BLUE</option>
<option value=" ">(Please, inform some color.)</option>
</datalist>

I'd like a quite simple solution because I am a novice programmer.

1

There are 1 best solutions below

0
user2314737 On

You can add an event listener to the input event that detects the input type (option selected or plain input) and then read the value of the element with id "input-color".

Demo:

// add event listener to the input event
window.addEventListener('input', function(e) {
  // detect input type (one of input or option selected)
  let event = e.inputType ? 'input' : 'option selected';
  datalist_value = document.getElementById("input-color").value;
  console.log(event, datalist_value);
}, false);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="input-color" list="color" autocomplete="off" required>
<datalist id="color">
<option>WHITE</option>
<option>BLACK</option>
<option>BLUE</option>
<option value=" ">(Please, input some color.)</option>
</datalist>

See also: Perform action when clicking HTML5 datalist option)