On click the input field, I do not want to display or show all the options or list. I just want to display while inputting some text only.
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<label for="browser">Choose your country:</label>
<input list="browsers" name="browser" id="browser">
<datalist id="browsers">
<option value="Australia">
<option value="USA">
<option value="Inda">
<option value="Bhutan">
<option value="Thailand">
<option value="Canada">
<option value="Japan">
<option value="China">
<option value="France">
</datalist>
</body>
</html>
CodePudding user response:
You can add an input
event listener that adds the list
attribute when the user types in the field. The id
of the datalist
can be stored in a data attribute.
$('input').on('input', function(){
const input = $(this)
if(input.val().length > 0){
input.attr('list', input.data('list'));
} else {
input.removeAttr('list');
}
})
<!DOCTYPE html>
<html>
<body>
<label for="browser">Choose your country:</label>
<input data-list="browsers" name="browser" id="browser">
<datalist id="browsers">
<option value="Australia">
<option value="USA">
<option value="Inda">
<option value="Bhutan">
<option value="Thailand">
<option value="Canada">
<option value="Japan">
<option value="China">
<option value="France">
</datalist>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</body>
</html>