2

When clicking the input field brings a dropdown like list. When trying to do the same with javascript click() it does not work. Why not? Can it be fixed?

document.querySelector('.button-click').addEventListener('click', () => {
  console.log('Event');
  document.querySelector('#my_list').click();
});

document.querySelector('.button-focus').addEventListener('click', () => {
  console.log('Event');
  document.querySelector('#my_list').focus();
});
<button class="button-click">Button to simulate click</button><br>
<button class="button-focus">Button to simulate focus</button><br>

<input list="list" id="my_list">
<datalist id="list">
  <option value="option1"></option>
  <option value="option2"></option>
 </datalist>

1 Answer 1

2

click() is not the correct method here. Use focus() instead and it works just fine. focus() mimics the behaviour of actually clicking inside the <input/> while click() only clicks onto the element.

document.querySelector('button').addEventListener('click', () => {
  console.log('Event');
  document.querySelector('#my_list').focus(); // <-- change this method
});
<button>Button</button>

<input list="list" id="my_list">
<datalist id="list">
  <option value="option1"></option>
  <option value="option2"></option>
</datalist>

Sign up to request clarification or add additional context in comments.

5 Comments

That set the focus on the input, but what I really want is the action from the input click which in this case is to bring the dropdown with the suggestions from the datalist.
Why do you want to explicitly do this with click(). It's a lot easier with the method that was made for that use case.
I don't really care about the method name I'm using. All I want is to trigger the dropdown with the options. Focus don't do that.
The longer I think about it, the more it looks like an XY-problem to me. I'm almost certain using focus is the way to go here and I still don't see any reason why it shouldn't be used. If you really want to use click (and make things twice as complicated), I recommend reading this post on How to show datalists with javascript?.
Alright. It seems not to be possible. I'll probably need to go with the next best thing which is :focus. At least I can show the user where to go with that hint. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.