0

If the try button is clicked should not the options be appeared?

<select id='test1'>
  <option>Option_1</option>
  <option>Option_2</option>
  <option>Option_3</option>
</select>
<button onclick='test1();'>try</button>
<script>
  function test1() {
    document.getElementById('test1').click();
  }
</script>
  • Why should options be appended? Clicking ` – Sebastian Simon Jul 09 '20 at 17:11
  • Do you want to open `select` using `button` ? – Rio A.P Jul 09 '20 at 17:14
  • 1
    It looks like the `click` event on the `` elements are closely tied with native host system functionality, I'm not sure if it's controllable in this manner. Why are you trying to do this? You may instead want to replace the ` – David Jul 09 '20 at 17:15
  • 1
    It was possible earlier but now its deprecated.. Please check this :: https://stackoverflow.com/questions/249192/how-can-you-programmatically-tell-an-html-select-to-drop-down-for-example-due – Akhil Jul 09 '20 at 17:21
  • David, I will automate a task for a website. I want to inject a little program in browser console for a website.@David – Miraj Khondokar Jul 09 '20 at 17:28
  • Yes @RapSherlock – Miraj Khondokar Jul 09 '20 at 17:30
  • To inject some code in browser console that will automate some task@user4642212 – Miraj Khondokar Jul 09 '20 at 17:31
  • 1
    @Akhil: Interesting find, and potentially a duplicate for this question. If I were to guess, I suspect in general browsers are reluctant to support dispatching such interactive events from code as it could quickly become a security problem with file inputs. – David Jul 09 '20 at 17:32
  • 1
    @MirajKhondokar: You may need to reconsider your approach for this automation. What's the underlying goal? You can *set the value* of the ` – David Jul 09 '20 at 17:33
  • @David: Setting the value of `` element for my so called automation. – Miraj Khondokar Jul 09 '20 at 17:57
  • @MirajKhondokar So why not just trigger the `change` event after setting the value? – Sebastian Simon Jul 09 '20 at 17:58
  • Can you set the value and trigger the change event as two separate steps? – David Jul 09 '20 at 17:58
  • If you change the value manually ( I mean by mouse) then change event is triggered. – Miraj Khondokar Jul 09 '20 at 18:04
  • how to do that in two separate steps? I don't know – Miraj Khondokar Jul 09 '20 at 18:05
  • 1
    @MirajKhondokar 1. Change the `` element. Googling either of these yields tons of results. – Sebastian Simon Jul 09 '20 at 18:06
  • @user4642212 ohh Understood! – Miraj Khondokar Jul 09 '20 at 18:10

1 Answers1

0

Unfortunately you can't do that. I suggest when you click the button, it changes to the next option.

function test1() {
    let el = document.getElementById('test1');
    let selectedIndex = el.selectedIndex;
    el.selectedIndex = selectedIndex + 1 === el.options.length ? 0 : selectedIndex + 1
}