7

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.

2
  • Do you want to show the dropdown or fetch selected dropdown option value? Commented Oct 29, 2013 at 7:27
  • Found something here Commented Oct 29, 2013 at 7:30

4 Answers 4

14

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.

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

9 Comments

This won't work for folks browsing with TAB on their keyboard.
this works only in Chrome...!!!!
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!
@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.
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...
|
4

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

1 Comment

Does not work in Firefox.
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

Comments

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.

3 Comments

We can open dropdown list..check this..jsfiddle.net/2wUjb/7
@Nikhil your solution is not working in Firefox and IE at least not for me.
oh..I am checking it in chrome..let me check into firefox and ie also.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.