5

Iam trying to show the dropdown option when javascript function is called. but eventually iam not succeed on this. need help Here is my code:

<script>
function showState(str){ 
$('#Acntname').trigger('click');

}
</script>
...
<select class="input_panel" id="Acntname" > 
<option value="0">Select</option>
<option value="1">Equity Share Capital</option>
<option value="2">Deprication Fund</option>  </select>

<input type="text" class="input_panel" id="accountname" onkeyup="showState(this.value)"/>

i used triggered function to open the dropdown but it doesn't work.

Sudarshan
  • 769
  • 6
  • 18
  • 33

4 Answers4

13

Here you go..you can do this by dispatching mousedown event on dropdown..

Demo Fiddle

JS:

window.showState = function (str) {
    var dropdown = document.getElementById('Acntname');
    var event = document.createEvent('MouseEvents');
    event.initMouseEvent('mousedown', true, true, window);
    dropdown.dispatchEvent(event);
}

EDIT: This works perfectly in Chrome <53, not sure for Firefox and IE.

loxx
  • 101
  • 4
nik
  • 4,439
  • 1
  • 32
  • 50
  • This won't work for folks browsing with TAB on their keyboard. – Sean Feb 11 '14 at 21:17
  • 1
    this works only in Chrome...!!!! – Mayank Pathak Apr 11 '14 at 05:07
  • 1
    This worked for me! I just used `dropdown.focus(); try { /* answer's chrome only code here */ } catch(e){}` to prevent it from messing anything up in Firefox/IE. Chrome only is better than nothing! – Luc Nov 02 '14 at 02:54
  • 2
    @smclark89 Actually, you can make it work with tab. Juse use a `keydown` event listener with `if (event.keyCode == 9 || event.keyCode == 13) { /* code here */ }` to capture the tab and enter keys. – Luc Nov 02 '14 at 02:58
  • this works in firefox 35.0.1 – P. Avery Feb 13 '15 at 22:11
  • Guys can u Please create Demo – Sopo Jan 05 '16 at 12:12
  • @Sopo Demo is here http://jsfiddle.net/2wUjb/7/ – nik Jan 11 '16 at 14:36
  • 2
    I tested it on Chrome Version 53.0.2785.101 (64-bit) and it does not work. It worked on Chrome Version 51.0.2704.106 (64-bit) though... – juacompe Sep 14 '16 at 11:07
2

You can do this:

var sel = document.getElementById('Acntname');
var len = sel.options.length;

sel.setAttribute('size', len);

Set the size back to 1 to close it

Peter Munnings
  • 3,269
  • 1
  • 28
  • 43
0

Its not possible to toggle the drop down on triggering other element.

If you want to select the value of select box on keyup event of textbox then try this,

function showState(str){ 
   //  alert(str);
   $('#Acntname option[value="'+str+'"]').prop('selected',true);
}

Demo

Rohan Kumar
  • 39,838
  • 11
  • 73
  • 103
0

You can't open the dropdown list but there is a semi-solution you could do the following

to "open" the list:

$("#Acntname").attr("size","3");

and

$("#Acntname").attr("size","1");

to close the list.

Ricky Stam
  • 2,028
  • 21
  • 25