Bruce
Bruce

Reputation: 1071

dropdown select on containing div click pure javascript

<div class="container">
  <select class="form_select">
    <option>the option</option>
  </select>
</div>

<style>
  .container {
    width: 300px;
    border:1px solid blue;
  }
  select {
    max-width:50px;
  }
</style>

I have a div containing a select option. The div is larger than the select box. Using a pure javascript solution, I would like the select dropdown to happen when the containing div is clicked outside the select box area. The only solutions I have found are jquery and I am seeking a pure javascript solution.

I don't need exact code (but it helps) as I am not very good with javascript so please explain any answer completely.

https://jsfiddle.net/m6s5j9sj/1/

Upvotes: 3

Views: 733

Answers (1)

brk
brk

Reputation: 50346

There may not be a simple way but you can try to set the size & length. The catch is it will only work if length is greater than 1. So in the demo I have created another option 'Select'.Hopefully in your application there will be multiple option

document.getElementById('container').addEventListener('click', function(e) {
  var seleOpt = document.getElementsByClassName('form_select')[0];
  seleOpt.size = seleOpt.options.length;
})
.container {
  width: 300px;
  border: 1px solid blue;
}

select {
  max-width: 50px;
}
<div class="container" id="container">
  <select class="form_select">
        <option>Select</option>
        <option>the option</option>
    </select>
</div>

Upvotes: 2

Related Questions